# 归并排序算法实现（C++）

如　设有数列{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

09-14 957

07-28 700

08-28 633

01-07 5535

08-23 3750

08-08 1095

12-11 4768

01-10 3249

10-07 3406

09-29 2359