# 归并排序的C++实现

1、划分子区间

2、合并子区间

 1 void merge_sort(int *data, int start, int end, int *result)
2 {
3     if(1 == end - start)//如果区间中只有两个元素，则对这两个元素进行排序
4     {
5         if(data[start] > data[end])
6         {
7             int temp  = data[start];
8             data[start] = data[end];
9             data[end] = temp;
10         }
11         return;
12     }
13     else if(0 == end - start)//如果只有一个元素，则不用排序
14         return;
15     else
16     {
17         //继续划分子区间，分别对左右子区间进行排序
18         merge_sort(data,start,(end-start+1)/2+start,result);
19         merge_sort(data,(end-start+1)/2+start+1,end,result);
20         //开始归并已经排好序的start到end之间的数据
21         merge(data,start,end,result);
22         //把排序后的区间数据复制到原始数据中去
23         for(int i = start;i <= end;++i)
24             data[i] = result[i];
25     }
26 }

merge的过程为：

 1 void merge(int *data,int start,int end,int *result)
2 {
3     int left_length = (end - start + 1) / 2 + 1;//左部分区间的数据元素的个数
4     int left_index = start;
5     int right_index = start + left_length;
6     int result_index = start;
7     while(left_index < start + left_length && right_index < end+1)
8     {
9         //对分别已经排好序的左区间和右区间进行合并
10         if(data[left_index] <= data[right_index])
11             result[result_index++] = data[left_index++];
12         else
13             result[result_index++] = data[right_index++];
14     }
15     while(left_index < start + left_length)
16         result[result_index++] = data[left_index++];
17     while(right_index < end+1)
18         result[result_index++] = data[right_index++];
19 }

 1 int main()
2 {
3     int data[] = {9,6,7,22,20,33,16,20};
4     const int length = 8;
5     int result[length];
6     cout << "Before sorted:" << endl;
7     for(int i = 0;i < length;++i)
8         cout << data[i] << "  ";
9     cout << endl;
10     cout << "After sorted:" << endl;
11     merge_sort(data,0,length-1,result);
12     for(int i = 0;i < length;++i)
13         cout << data[i] << "  ";
14     cout << endl;
15
16     return 0;
17 }

posted @ 2015-05-09 14:34  RIO_2607  阅读(45549)  评论(0编辑  收藏  举报