归并操作(merge),也叫归并算法,指的是将两个已经排序的序列合并成一个序列的操作[1]。
如 设有数列{6,202,100,301,38,8,1}
初始状态: [6] [202] [100] [301] [38] [8] [1] 比较次数
i=1 [6 202 ] [ 100 301] [ 8 38] [ 1 ] 3
i=2 [ 6 100 202 301 ] [ 1 8 38 ] 4
i=3 [ 1 6 8 38 100 202 301 ] 4
根据例子实现的算法为:
#include <iostream>
using namespace std;
int a[] = {6,202,100,301,38,8,1};
void merge_array(int a[], int n, int b[],int m, int c[]);
void merge_sort(int a[], int first, int last, int temp[]);
int main()
{
cout<<"Before Sort: ";
for(int i=0; i<7; i++)
cout<<a[i]<<" ";
cout<<endl;
int temp[7];
merge_sort(a,0,6,temp);
cout<<"After Sort: ";
for(int i=0; i<7; i++)
cout<<a[i]<<" ";
cout<<endl;
system("pause");
}
void merge_array(int a[], int first, int mid,int last, int c[])
{
int i = first ,j = mid+1,k=0;
while(i<=mid && j<=last)
{
if(a[i]>a[j])
c[k++] = a[j++];
else
c[k++] = a[i++];
}
while(i<=mid)
c[k++] = a[i++];
while(j<=last)
c[k++] = a[j++];
for(int x = 0; x<k; x++)
a[first+x] = c[x];
}
void merge_sort(int a[], int first, int last, int temp[])
{
if(first<last)
{
int mid = (first+last)/2;
merge_sort(a, first, mid, temp);
merge_sort(a, mid+1, last, temp);
merge_array(a, first, mid, last, temp);
}
}
[1]百度百科 http://baike.baidu.com/view/90797.htm