归并排序
归并排序是使用一种divide-and-conquer(分而治之)的方式,通过将一个长的数组先进行划分,然后再将他们整合在一起,从而达到基于部分而获得整体的效果
归并排序的实现方法
归并排序(Merge sort)是建立在归并操作上的一种有效的排序算法。
-
作为一种典型的分而治之思想的算法应用,归并排序的实现由两种方法:
-
自上而下的递归(所有递归的方法都可以用迭代重写,所以就有了第 2 种方法);
自下而上的迭代;
However, it is not possible to do so in JavaScript, as the recursion goes too deep for the language to handle.
然而,在 JavaScript 中这种方式不太可行,因为这个算法的递归深度对它来讲太深了。
这里引用一下hackerearth上面对于归并的图:
归并排序的复杂度分析
- 时间复杂度:o(nlogn)
总时间=分解时间+解决问题时间+合并时间。分解时间就是把一个待排序序列分解成两序列,时间为一常数,时间复杂度o(1).解决问题时间是两个递归式,把一个规模为n的问题分成两个规模分别为n/2的子问题,时间为2T(n/2).合并时间复杂度为o(n)。总时间T(n)=2T(n/2)+o(n).这个递归式可以用递归树来解,其解是o(nlogn).此外在最坏、最佳、平均情况下归并排序时间复杂度均为o(nlogn).从合并过程中可以看出合并排序稳定。
Java代码的实现
public class MergeSort {
public static void main(String[] args) {
int[] test = {9,2,6,3,5,7,10,11,12};
mergeSort(test,0,test.length-1);
for(int i=0; i<test.length;i++){
System.out.print(test[i] + " ");
}
}
public static void mergeSort(int[] arry,int left,int right){
if(left<right){
int mid = (left+right)/2;
//int mid=left+(right-left)/2; //防止数组越界
mergeSort(arry,left,mid);//左归并排序,有序化左子序列
mergeSort(arry,mid+1,right);//右归并排序,有序化右子序列
merge(arry,left,mid,right);//合并两个序列
}
}
private static void merge(int[] arry,int left,int mid,int right){
int[] temp=new int[right-left+1];//创建一个新的数组
int i=left;
int j=mid+1;
int k=0;
while (i<=mid&&j<=right){
if (arry[i]<arry[j]){ //说明这里是一个顺序对
temp[k++]=arry[i++];
}else {
temp[k++]=arry[j++];
}
}
while (i<=mid){
temp[k++]=arry[i++];
}
while (j<=right){
temp[k++]=arry[j++];
}
//System.arraycopy(temp,0,arry,left,right-left+1);
//将temp中的元素全部拷贝到原数组中
for (int k2 = 0; k2 < temp.length; k2++) {
arry[k2 + left] = temp[k2];
}
}
}