归并排序
排序过程:将数组不断的分割,最终分成只有两个数的序列,然后对这些序列进行排序,再将这些序列进行合并
public void sorting() {
mergeSorting(0,array.length-1);
}
private void mergeSorting(int low,int high){
if(low<high){
int mid=(low+high)/2;
mergeSorting(low,mid);
mergeSorting(mid+1,high);
merge(low,high);
}
}
//两个数组合并
private void merge(int low,int high){
int mid=(high+low)/2;
int[] temp=new int[high-low+1];
int k=0,i=0,j=0;
for(i=low,j=mid+1;i<=mid&&j<=high;){
if(array[i]<=array[j]){
temp[k++]=array[i++];
}else if(array[i]>array[j]){
temp[k++]=array[j++];
}
}
//循环结束,如果还有没有复制完的数据
while(i<=mid){
temp[k++]=array[i++];
}
while(j<=high){
temp[k++]=array[j++];
}
for(i=low;i<=high;i++){
array[i]=temp[i-low];
}
}
时间复杂度: 平均O(nlogn) 最好O(nlogn) 最坏O(nlogn) 稳定
代码下载:

浙公网安备 33010602011771号