归并排序的主要思想:
(1)将一个完整的数组一直分啊分,分成一个个小数组,分到每个数组只有一个元素它就自然有序了
(2)然后再将这些数组合并成一个数组
总的来说就是 分治 + 合并
我们来看看代码吧!
/**
* 归并排序(分治 合并 思想)
*
*
* */
public static void MergeArray(int[]array,int left,int mid,int right,int[] temp){
int i = left, j =mid+1;
int m = mid , n = right;
int k = 0;
// 二路归并
// 将两个有序数组合并成一个有序数组
while (i <= m && j <= n){
if (array[i]<=array[j])
temp[k++] = array[i++];
else
temp[k++] = array[j++];
}
// 将剩余元素放到临时数组里面
while (i <= m)
temp[k++] = array[i++];
while (j <= n)
temp[k++] = array[j++];
// 将临时数据copy到目标数组
for ( i = 0; i < k; i++){
array[i+left] = temp[i];
}
}
public static void MergeSort(int[] array,int left,int right,int[] temp){
if (left >= right)
return;
int mid = left + ( right - left )/2;
// 此处采用递归的做法,一直分,分到只有一个元素,它自然就有序了
MergeSort(array,left,mid,temp); // 为啥是二路归并呢?就是它每次从中间将一个数组分成了两个
MergeSort(array,mid+1,right,temp);
MergeArray(array,left,mid,right,temp);// 然后我们来合并这些数组
}
结果:
69 58 92 72 22 28 8 64 38 42
8 22 28 38 42 58 64 69 72 92