快速排序
public static void QSort(int [] datas,int start,int end){ if(start < end) { int mid = Partition(datas,start,end); QSort(datas,start,mid); QSort(datas,mid+1,end); } } public static int Partition(int[] datas,int start,int end){ int midKey = datas[start]; int left = start,right = end; while (left<right){ while (left<right && datas[right]>=midKey) right--; datas[left] = datas[right]; while (left<right && datas[left]<=midKey) left++; datas[right] = datas[left]; } datas[left] = midKey; return left; } public static void main(String[] args){ int[] datas = new int[]{5,4,7,3,2}; QSort(datas,0,datas.length-1); for(int i:datas) { System.out.println(i); } }
归并排序
public static void MergeSort(int [] datas,int start,int end){ if(start<end){ int mid = (start+end)/2; MergeSort(datas,start,mid); MergeSort(datas,mid+1,end); Merge(datas,start,mid,end); } } public static void Merge(int []datas,int start,int mid,int end ){ int []copy = new int[datas.length]; int left = start,right=mid+1,index=start; while(left<=mid && right<=end){ if(datas[left]<=datas[right]) copy[index++]=datas[left++]; else copy[index++]= datas[right++]; } if(left<=mid) while (left<=mid) copy[index++] = datas[left++]; if(right<=end) while (right<=end) copy[index++] = datas[right++]; for(int i=start;i<=end;i++){ datas[i] = copy[i]; } } public static void main(String[] args){ int[] datas = {6, 7, 3, 2, 7, 46, 78}; MergeSort(datas,0,datas.length-1); for(int i:datas) { System.out.println(i); } }
堆排序
public static void HeapSort(int []datas,int root,int length){ for(int i=length/2;i>0;i--){ HeapAdjust(datas,i,length); } for(int j=length;j>1;j--){ datas[1] = datas[j]^datas[1]; datas[j] = datas[j]^datas[1]; datas[1] = datas[j]^datas[1]; HeapAdjust(datas,1,j-1); } } public static void HeapAdjust(int []datas,int root,int length){ int temp = datas[root]; int start = root; for(int i=2* start;i<=length;i=2*start){ if((i+1)<=length&&datas[i]<datas[i+1]) i++; if(temp>=datas[i]) break; datas[start]=datas[i]; start=i; } datas[start]=temp; } public static void main(String[] args){ int[] datas = new int[]{0,1,2,7,4,5,6,5,3}; HeapSort(datas,0,datas.length-1); for(int i:datas) { System.out.println(i); } }