程序
/**
*@descript : 归并排序
*@author : chenzx
*@copyright: 2012-12-3(c++)
*/
#include <iostream>
using namespace std;
const int N = 7;
void print_arry(int * arry, int len){
for (int i = 0; i < len; i++)
{
cout<<arry[i]<<" ";
}
cout<<endl;
}
/* 将已序的fist->mid-1, 和mid->last 归并在一起 */
void merge_arry(int arry[], int first, int mid, int last){
int first1 = first, last1 = mid ; //定义左有序序列的起始结束位置
int first2 = mid + 1, last2 = last; //定义右有序序列的起始结束位置
int *temp = new int[last - first + 1]; //分配临时保存的空间
int index = 0;
//1. 将两个序列归并到临时数组中
while((first1 <= mid) && (first2 <= last)){
if (arry[first1] < arry[first2]){
temp[index++] = arry[first1++];
}else{
temp[index++] = arry[first2++];
}
}
//2. 将剩余的部分添加到临时数组中
while(first1 <= mid){
temp[index++] = arry[first1++];
}
while(first2 <= last){
temp[index++] = arry[first2++];
}
// print_arry(temp, last- first + 1);
//3. 将临时数组中的内容返回给arry
index = 0;
for (int i = first; i <= last; i++){
arry[i] = temp[index++];
}
delete[] temp;
}
/* 使用递推将序列first->last 序列进行归并排序 */
void merge_sort(int * arry, int first, int last){
int mid = 0;
if (first < last)
{
mid = (first + last)/2;
merge_sort(arry, first, mid);
merge_sort(arry, mid + 1, last);
merge_arry(arry,first, mid, last);
}
//print_arry(arry,N);
}
int main()
{
cout<<"This is merge sort!"<<endl;
int arry[N] = {3,5,8,1,2,7,4};
cout<<"The orige number :"<<endl;
print_arry(arry, N);
merge_sort(arry, 0, N - 1);
cout<<"The sort number :"<<endl;
print_arry(arry, N);
system("pause");
return 0;
}
效果图
算法复杂度分析
1) 归并递归的一般公式