各种排序算法
只有代码,
package 各种排序算法; public class Test { public static void main(String[] args) { // TODO Auto-generated method stub int[] a = {3,4,2,33,55,66,234,234,653,43,6}; long s = System.currentTimeMillis(); int[]temp = new int[a.length]; //insert_sort(a); shell_sort(a); System.out.println(System.currentTimeMillis()-s); for(int i = 0; i<a.length; i++) { System.out.print(a[i]+" "); } } // 快排 public static void quick_sort(int[] a,int start,int end) { if(start>=end) return; int i = start; int j = end; int key = a[start]; while(i<j) { while(i<j&&a[j]>=key) { j--; } a[i] = a[j]; while(i<j&&a[i]<=key) { i++; } a[j] = a[i]; } a[i] = key; quick_sort(a, start, i-1); quick_sort(a, i+1, end); } // 冒泡排序 public static void bubble_sort(int[] a) { for(int i = 0; i<a.length;i++) { boolean flag = true; for(int j = 0; j<a.length-1-i;j++) { if(a[j]>a[j+1]) { int temp = a[j]; a[j] = a[j+1]; a[j+1] = temp; flag = false; } } if(flag) break; } } // 选择排序 public static void selective_sort(int[] a) { for(int i = 0 ; i<a.length; i++) { int min = a[i]; int k = i; for(int j = i; j<a.length;j++) { if(a[j]<min) { k = j; min = a[j]; } } if(k!=i) { int temp = a[k]; a[k] = a[i]; a[i] = temp; } } } // 插入排序 public static void insert_sort(int[] a) { if(a.length == 0|| a.length == 1) return; for(int i = 1; i<a.length; i++) { int temp = a[i]; int j = i-1; while(j>=0&&a[j]>temp) { a[j+1] = a[j]; j-=1; } a[j+1] = temp; } } // 希尔排序 (插入排序增强版 每次改变插入间隙) public static void shell_sort(int[] a) { for(int d = a.length/2;d>=1;d = d/2) { for(int i = d; i<a.length;i++) { int temp = a[i]; int j = i-d; while(j>=0&&a[j]>temp) { a[j+d] = a[j]; j-=d; } // for(;j>=0&&a[j]>temp;j-=d) // { // a[j+d] = a[j]; // } a[j+d] = temp; } } } //归并排序 public static void merge(int[] a,int first,int mid, int end, int[] temp) { int i = first; int j = mid+1; int m = mid; int k = 0; while(i<=m&&j<=end) { if(a[i]<a[j]) { temp[k++] = a[i]; i++; } else{ temp[k++] = a[j]; j++; } } while(i<=mid) { temp[k++] = a[i++]; } while(j<=end) { temp[k++] = a[j++]; } for(i = 0; i<k;i++) { a[i+first] = temp[i]; } } public static void merge_sort(int a[] , int first, int end,int[] temp) { if(first<end) { int mid =( end+first)/2; merge_sort(a, first, mid, temp); merge_sort(a, mid+1, end, temp); merge(a, first, mid, end, temp); } } // 堆排序 public static void heapAdjust(int a[],int i,int length) { for(int temp = a[i];2*i+1<length;) { int l_child = 2*i+1; if(l_child+1<length&&a[l_child]<a[l_child+1]) l_child++; if(temp<a[l_child]) { a[i] = a[l_child]; a[l_child] = temp; i = l_child; } else { break; } } } public static void heap_sort(int[]a) { //建堆 for(int i = a.length/2-1;i>=0;i--) { heapAdjust(a, i,a.length); } // 排序 for(int i = a.length-1; i>0;i--) { int temp = a[0]; a[0] = a[i]; a[i] = temp; heapAdjust(a, 0,i); } } }