void MergeSort(int* data, int length)
{
if(data == NULL || length <= 0) return;
int *copy = new int[length];
int* arr[2] = {data, copy};
int cur = 0;
//steps为步长,将arr[cur]分组,每组steps个,然后两两merge到arr[1-cur]
//steps < length能保证最后肯定被分成两组
for(int steps = 1; steps < length; steps *= 2)
{
//假设merge的两个分组为[left_min,left_max],[right_min,right_max]
int left_min, left_max, right_min, right_max;
int k;
//length - left_min为还没有merge的元素个数,它们应该至少能分两组,才继续进行么merge
for(left_min = 0; steps < length - left_min; left_min = right_max + 1)
{
left_max = left_min + steps - 1;
right_min = left_max + 1;
right_max = right_min + steps - 1;
if(right_max >= length) right_max = length - 1;
k = left_min;
while(left_min <= left_max && right_min <= right_max)
{
if(arr[cur][left_min] <= arr[cur][right_min])
arr[1-cur][k++] = arr[cur][left_min++];
else arr[1-cur][k++] = arr[cur][right_min++];
}
while(left_min <= left_max)
arr[1-cur][k++] = arr[cur][left_min++];
while(right_min <= right_max)
arr[1-cur][k++] = arr[cur][right_min++];
}
//当有奇数个分组时,最后一个分组没有被merge,但要从arr[cur]拷贝到arr[1-cur]
while(left_min < length)
arr[1-cur][k++] = arr[cur][left_min++];
cur = 1 - cur;
}
for(int i = 0; i < length; i++)
arr[1-cur][i] = arr[cur][i];
delete[] copy;
}
数组的归并排序(使用Ο(n)的辅助空间,循环)
最新推荐文章于 2023-07-07 21:18:14 发布