数据结构和算法基础之归并排序
////// 归并排序 /// public static void MergetSort(int[] arry,int first,int end) { if(first<end) { int mid = (end + first) / 2; MergetSort(arry, first, mid); MergetSort(arry, mid+1, end); Merging(arry, first, mid, end); } } public static void Merging(int[] arry,int first,int mid,int end) { int[] tmp = new int[end - first + 1]; int tmpIndex = 0; int start = first; int n = mid+1; while(start<=mid&&n<end) { if(arry[start]<arry[n]) { tmp[tmpIndex] = arry[start]; start++; tmpIndex++; }else { tmp[tmpIndex] = arry[n]; n++; tmpIndex++; } } while (start <=mid) { tmp[tmpIndex] = arry[start]; start++; tmpIndex++; } while (n<end) { tmp[tmpIndex] = arry[n]; n++; tmpIndex++; } for ( tmpIndex = 0,start=first;start ) { arry[start] = tmp[tmpIndex]; } }
时间复杂度:nlog(n)