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)。