下面的java程序的两个函数实现了快排与归并排序
快排 实现的是就地排序,归并需要重新申请内存空间,在归并排序的实现中,最初采用的是 int[] copy = num , 出错后调试发现时浅拷贝?
public class Algorithm {
public static void quickSort(int[] num, int i, int j){
if(i<j){
int q = i-1;
int k = num[j];
for(int h = i; h<=j; h++){
if(num[h]<k){
// exchange num[q+1] and num[h]
int tmp = num[q+1];
num[q+1] = num[h];
num[h] = tmp;
q++;
}
}
// set num[j] = num[q+1]
num[j] = num[q+1];
// partition num[q+1] every turn
num[q+1] = k;
quickSort(num,i,q);
quickSort(num,q+2,j);
}
}
public static void mergeSort(int[] num,int i,int j,int[] copy){
if(i<j){
int medium = (i+j)/2;
mergeSort(num,i,medium,copy);
mergeSort(num,medium+1,j,copy);
int p = i;
int h = i;
int k = medium + 1;
while(h<=medium&&k<=j){
if(num[h] < num[k]){
copy[p++] = num[h++];
}else{
copy[p++] = num[k++];
}
}
while((k==j+1)&&h<=medium){
copy[p++] = num[h++];
}
while((h==j+1)&&k<=j){
copy[p++] = num[k++];
}
for(int l=i;l<=j;l++){
num[l]=copy[l];
}
}
}
public static void main(String[] args){
int[] num = {7,3,2,8,6,5};
int[] copy = new int[num.length];
mergeSort(num,0,num.length-1,copy);
for(int i=0;i<num.length;i++){
System.out.println(num[i]);
}
}
}