排序最终版

来源:互联网 发布:js跳转页面 编辑:程序博客网 时间:2024/06/10 03:03


简单排序:

 public static void selectionSort(int[] number) {        for(int i = 0; i < number.length - 1; i++) {             int m = i;             for(int j = i + 1; j < number.length; j++)                 if(number[j] < number[m])                     m = j;             if(i != m)                 swap(number, i, m);        }    }



  public static void injectionSort(int[] number) {         for(int j = 1; j < number.length; j++) {             int tmp = number[j];             int i = j - 1;             while(tmp < number[i]) {                number[i+1] = number[i];                 i--;                 if(i == -1)                     break;             }                         number[i+1] = tmp;         }     }



 public static void bubbleSort(int[] number) {        boolean flag = true;         for(int i = 0; i < number.length-1 && flag; i++) {             flag = false;             for(int j = 0; j < number.length-i-1; j++) {                 if(number[j+1] < number[j]) {                     swap(number, j+1, j);                     flag = true;                 }             }         }    }

 

快速排序

public static int partition(int[] a,int left,int right){int pivot = a[left];while(left<right){while(left<right&&a[right]>pivot)right--;if(left<right)a[left++] = a[right];while(left<right&&a[left]<pivot)left++;if(left<right)a[right--] = a[left];}a[left] = pivot;return left;}public static void sort(int[]a,int left,int right){if(left<right){int partition = partition(a, left, right);sort(a,left,partition-1);sort(a,partition+1,right);}}

归并排序

private static void sort(Int[] a , int left, int right) { if (left < right) {int center = (left + right) / 2;sort(a, left, center); sort(a, center + 1, right); merge(a, left, center, right); System.out.println(java.util.Aays.toString(a));} }  private static void merge(Int[] a, int left, int center, int right) {//定义一个与待排序序列长度相同的临时数组 Int[] tmpA = new Int[a.length];int mid = center + 1;//third记录中间数组的索引int third = left; int tmp = left; while (left <= center && mid <= right) { //从两个数组中取出小的放入中间数组 if (a[left].compareTo(a[mid]) <= 0) { tmpA[third++] = a[left++]; } else{tmpA[third++] = a[mid++]; }} //剩余部分依次放入中间数组 while (mid <= right) { tmpA[third++] = a[mid++]; } while (left <= center) { tmpA[third++] = a[left++]; } //将中间数组中的内容复制拷回原数组//(原left~right范围的内容复制回原数组) while (tmp <= right){a[tmp] = tmpA[tmp++]; }}


堆排序

 

public static void adjust(int[] a,int root,int n){int child = 2*root;int rootkey = a[root];while(child <= n){if(child<n&&a[child]<a[child+1]){child++;}if(rootkey>a[child])break;else{a[child/2] = a[child];child*=2;}}a[child/2] = rootkey;}public static void sort(int[] a,int n){for(int i = n/2; i>0; i--)adjust(a,i,n);for(int i = n-1; i>0; i--){swap(a,1,i+1);adjust(a,1, i);}}


 

 

当N较小可采用直接插入,冒泡,简单学则排序

当关键字正向有序时选择直接插入,冒泡

链式不宜采用快速排序,堆排序。

稳定:插入,冒泡,归并


 



 

原创粉丝点击