package sort;
/**
* MergeSort
* 归并排序算法:
* 1.申请空间,使其大小为两个已经排序序列之和,该空间用来存放合并后的序列
* 2.设定两个指针,最初位置分别为两个已经排序序列的起始位置
* 3.比较两个指针所指向的元素,选择相对小的元素放入到合并空间,并移动指针到下一位置
* 4.重复步骤3直到某一指针达到序列尾 5.将另一序列剩下的所有元素直接复制到合并序列尾
*
*/
public class MergeSort
{
private int countStep = 0;
public void sort(int[] initData)
{
int len = initData.length;
mergeSort(initData, 0, len - 1);
}
public int showStep()
{
return countStep;
}
private void mergeSort(int[] array, int from, int to)
{
if (to <= from)
{
return;
}
int middle = (from + to) / 2;
mergeSort(array, from, middle);
mergeSort(array, middle + 1, to);
merge(array, from, to, middle);
}
private void merge(int[] array, int from, int to, int middle)
{
int[] tempArray = new int[array.length];
int temp = from;
int midRight = middle + 1;
int copyFrom = from;
while (from <= middle && midRight <= to)
{
if (array[from] < array[midRight])
{
tempArray[temp++] = array[from++];
}
else
{
tempArray[temp++] = array[midRight++];
}
countStep ++;
}
while (from <= middle)
{
tempArray[temp++] = array[from++];
countStep ++;
}
while (midRight <= to)
{
tempArray[temp++] = array[midRight++];
countStep ++;
}
//copy tempArray to array
while (copyFrom <= to)
{
array[copyFrom] = tempArray[copyFrom];
copyFrom ++;
countStep ++;
}
}
}
归并排序算法
最新推荐文章于 2023-03-25 00:51:13 发布