美文网首页
android 随笔之排序算法

android 随笔之排序算法

作者: android老菜鸟 | 来源:发表于2019-01-04 14:50 被阅读0次

    1,冒泡排序(1)

    public static void BubbleSort1(int [] arr){
            int temp;//临时变量
            boolean flag;//是否交换的标志
            for(int i=0; i<arr.length-1; i++){   //表示趟数,一共arr.length-1次。
                flag = false;
                for(int j=arr.length-1; j>i; j--){
                    if(arr[j] < arr[j-1]){
                        temp = arr[j];
                        arr[j] = arr[j-1];
                        arr[j-1] = temp;
                        flag = true;
                    }
                }
                if(!flag) break;
            }
        }
    

    冒泡排序(2)

        public static void BubbleSort2(int[] arr) {
            int temp;//临时变量
            for (int i = 0; i < arr.length - 1; ++i) {
                for (int j = 0; j < arr.length - i - 1; ++j) {
                    if (arr[j] > arr[j + 1]) {
                        temp = arr[j];
                        arr[j] = arr[j + 1];
                        arr[j + 1] = temp;
                    }
                }
            }
        }
    

    2,选择排序

          for(int i=0;i<lenth-1;i++){
              int minIndex = i;
              for(int j=i+1;j<lenth;j++){
                 if(array[j]<array[minIndex]){
                     minIndex = j;
                 }
              }
              if(minIndex != i){
                  int temp = array[i];
                  array[i] = array[minIndex];
                  array[minIndex] = temp;
              }
          }
      }
    

    3,插入排序

          int temp;
          for(int i=0;i<lenth-1;i++){
              for(int j=i+1;j>0;j--){
                  if(array[j] < array[j-1]){
                      temp = array[j-1];
                      array[j-1] = array[j];
                      array[j] = temp;
                  }else{ //不需要交换
                      break;
                  }
              }
          }
      }
    

    4,快速排序

            if(l>=r)
              return;
            int i = l; int j = r; int key = a[l];//选择第一个数为key
            while(i<j){
                while(i<j && a[j]>=key)//从右向左找第一个小于key的值
                    j--;
                if(i<j){
                    a[i] = a[j];
                    i++;
                }
                while(i<j && a[i]<key)//从左向右找第一个大于key的值
                    i++;
                if(i<j){
                    a[j] = a[i];
                    j--;
                }
            }
            //i == j
            a[i] = key;
            quickSort(a, l, i-1);//递归调用
            quickSort(a, i+1, r);//递归调用
        }
    

    相关文章

      网友评论

          本文标题:android 随笔之排序算法

          本文链接:https://www.haomeiwen.com/subject/ttahrqtx.html