java七大排序——7_归并排序
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了java七大排序——7_归并排序相关的知识,希望对你有一定的参考价值。
归并排序:将数组分为2块,再到每一小块再分为两块,直到最后一个元素为一块,然后进行有序数组合并,最终合并为一个有序数组
代码实现
public static void mergeSorts ( int[] array)
mergeSortsInternal(array,0,array.length)
//mergeSortsInternalNoR(array);
/**
* 归并排序:递归内部排序
*/
public static void mergeSortInternal ( int[] array, int low, int high)
if (low + 1 >= high) //[low,high)
return;
int mid = (low + high) / 2;
mergeSortInternal(array, low, mid);
mergeSortInternal(array, mid, high);
merge(array, low, mid, high);
private static void merge ( int[] array, int low, int mid, int high)
int length = high - low;
int[] extral = new int[length];
//[low,mid]
//[mid,high]
int less = low;
int great = mid;
int i = 0;
while (less < mid && great < high)
if (array[less] <= array[great])
extral[i] = array[less];
less++;
i++;
else
extral[i] = array[great];
great++;
i++;
while (less < mid)
extral[i++] = array[less++];
while (great < high)
extral[i++] = array[great++];
for (int j = 0; j < length; j++)
array[low + j] = extral[j];
以上是关于java七大排序——7_归并排序的主要内容,如果未能解决你的问题,请参考以下文章