【排序】3.归并排序
建立在归并操作上的一种有效的排序算法,采用分治法思想
将已有序的子序列合并,得到完全有序的序列,二路归并
public static void sort(int a[],int start,int end){//递归分区 int mid=(start+end)/2; if(start<end){ sort(a,start,mid); sort(a,mid+1,end); marge(a,start,mid,end); } } private static void marge(int[] a, int start, int mid, int end) { int[] temp=new int[end-start+1];//合并两个分区 int s=start; int m=mid+1; int e=end; int i=0; while(s<=mid&&m<=end){ if (a[s]<a[m]) { temp[i]=a[m]; i++; m++; } else{ temp[i]=a[s]; i++; s++; } } while(s<=mid){ temp[i]=a[s]; i++; s++; } while(m<=end){ temp[i]=a[m]; i++; m++; } for (int j = 0; j < temp.length; j++) {//将临时数组中的数据复制到原数组 a[start+j]=temp[j]; } }
归并排序是一种稳定的排序,速度仅次于快速排序
一般用于总体无序,但各子项相对有序的数列
时间复杂度:O(nlog₂n)
空间复杂度:O(n)