1、测试代码
#include <iostream>
using namespace std;
int g_loop = 0; /* 循环计数 */
int g_move = 0; /* 数据移动次数 */
void output_info(int *buff,int len, int flag)
{
int i;
if(0 == flag)
{
cout << "buff: ";
}
else
{
cout << "temp: ";
}
for(i = 0; i < len; ++i)
{
cout << *(buff + i) << " ";
}
cout << endl;
}
void merge(int arr[], int left,int mid,int right,int temp[])
{
int i = left; // 左序列指针
int j = mid + 1; // 右序列指针
int pos = 0; // 临时数组指针
while (i <= mid && j <= right)
{
if(arr[i] <= arr[j])
{
temp[pos++] = arr[i++];
}
else
{
temp[pos++] = arr[j++];
}
}
while(i <= mid) // 将左数组剩余元素放进temp中
{
temp[pos++] = arr[i++];
}
while(j <= right) // 将右数组剩余元素放进temp中
{
temp[pos++] = arr[j++];
}
//将temp中的元素全部拷贝到原数组中
output_info(arr, 10, 0);
pos = 0;
while(left <= right)
{
arr[left++] = temp[pos++];
++g_move;
}
output_info(temp, 10, 1);
}
void spread_out(int *buff, int left,int right, int *temp)
{
int mid;
++g_loop;
if(right > left)
{
mid = left + (right - left) / 2;
spread_out(buff, left, mid, temp);
spread_out(buff, mid + 1, right, temp);
merge(buff, left, mid, right, temp);
}
if(right - left == 1) /* 左右数组中只有一个数据 */
{
cout<< "left=" << *(buff + left) << " right=" << *(buff + right) << " end"<<endl;
}
else if(right - left == 0) /* 左数组中有一个数据,右数组空 */
{
cout<< "left=" << *(buff + left) << " end"<<endl;
}
cout<<endl;
}
/* 归并排序 */
int main()
{
int array[10]= {10,9,8,7,6,5,4,3,2,1};
int temp[10]= {0};
spread_out(array, 0 ,9, temp);
output_info(array, 10, 0);
cout << endl;
cout << "move=" << g_move << endl;
cout << "loop=" << g_loop << endl;
return 0;
}
2、测试log
left=10 end
left=9 end
buff: 10 9 8 7 6 5 4 3 2 1
temp: 9 10 0 0 0 0 0 0 0 0
left=9 right=10 end
left=8 end
buff: 9 10 8 7 6 5 4 3 2 1
temp: 8 9 10 0 0 0 0 0 0 0
left=7 end
left=6 end
buff: 8 9 10 7 6 5 4 3 2 1
temp: 6 7 10 0 0 0 0 0 0 0
left=6 right=7 end
buff: 8 9 10 6 7 5 4 3 2 1
temp: 6 7 8 9 10 0 0 0 0 0
left=5 end
left=4 end
buff: 6 7 8 9 10 5 4 3 2 1
temp: 4 5 8 9 10 0 0 0 0 0
left=4 right=5 end
left=3 end
buff: 6 7 8 9 10 4 5 3 2 1
temp: 3 4 5 9 10 0 0 0 0 0
left=2 end
left=1 end
buff: 6 7 8 9 10 3 4 5 2 1
temp: 1 2 5 9 10 0 0 0 0 0
left=1 right=2 end
buff: 6 7 8 9 10 3 4 5 1 2
temp: 1 2 3 4 5 0 0 0 0 0
buff: 6 7 8 9 10 1 2 3 4 5
temp: 1 2 3 4 5 6 7 8 9 10
buff: 1 2 3 4 5 6 7 8 9 10
move=34
loop=19
3、算法分析
- 非原地排序算法;
- 稳定排序算法;
- 空间复杂度 O(n);
- 时间复杂度 O(nlogn)。