int h = 1;
while(h < n/3) h = h*3 + 1;
while(h >= 1) {
for(int i = h; i < n; i++) {
for(int j = i; j >= h && nums[j] < nums[j-h]; j -= h) {
swap(nums,j,j-h);
}
}
h = h/3;
}
归并排序
自顶向下的归并排序
public class MergeSort {
private static int[] aux;
public static void sort(int[] nums) {
aux = new int[nums.length];
sort(nums,0,nums.length-1);
}
private static void sort(int[] nums,int lo,int hi) {
if(lo >= hi) return;
int mid = (lo + hi)/2;
sort(nums,lo,mid);
sort(nums,mid+1,hi);
merge(nums,lo,mid,hi);
}
private static void merge(int[] nums,int lo,int mid,int hi) {
for(int i = lo; i <= hi; i++) {
aux[i] = nums[i];
}
int left = lo;
int right = mid+1;
for(int i = lo; i <= hi; i++) {
if(left > mid) nums[i] = aux[right++];
else if(right > hi) nums[i] = aux[left++];
else if(aux[left] <= aux[right]) nums[i] = aux[left++];
else nums[i] = aux[right++];
}
}
}
自底向上的归并排序
public class MergeSort {
private int[] aux;
public static void sort(int[] nums) {
int len = nums.length;
aux = new int[len];
for(int sz = 1; sz < len; sz += sz) {
for(int lo = 0; lo < len - sz; lo += sz + sz) {
merge(nums,lo,lo+sz-1,Math.min(lo+sz+sz-1,len-1));
}
}
}
}
快速排序
public class QuickSort {
public static void sort(int[] nums) {
sort(nums,0,a.length-1);
}
private static void sort(int[] nums,int lo,int hi) {
if(lo >= hi) return;
int j = partition(nums,lo,hi);
sort(nums,lo,j-1);
sort(nums,j+1,hi);
}
private static int partition(int[] nums,int lo,int hi) {
int i = lo,j = hi+1;
int key = a[lo];
while(true){
while(a[++i] < key && i < hi);
while(a[--j] > key && j > lo);
if(i >= j) break;
exch(nums,i,j);
}
exch(nums,lo,j);
return j;
}
}