Chinaunix首页 | 论坛 | 博客
  • 博客访问: 161750
  • 博文数量: 76
  • 博客积分: 1513
  • 博客等级: 上尉
  • 技术积分: 755
  • 用 户 组: 普通用户
  • 注册时间: 2011-11-25 15:15
文章分类

全部博文(76)

文章存档

2012年(2)

2011年(74)

我的朋友

分类: C/C++

2012-04-28 09:46:21


点击(此处)折叠或打开

  1. #include <iostream>
  2. using namespace std;


  3. void Merge(int a[], int b[], int low, int mid, int high)
  4. {
  5.     int k = low;
  6.     int begin1 = low;
  7.     int end1 = mid;
  8.     int begin2 = mid + 1;
  9.     int end2 = high;
  10.     while(begin1 <= end1 && begin2 <= end2)
  11.     {
  12.         if(a[begin1] <= a[begin2])
  13.             b[k++] = a[begin1++];
  14.         else
  15.             b[k++] = a[begin2++];
  16.     }
  17.     if(begin1 <= end1)
  18.         for(int q = begin1; q <= end1; q++)
  19.             b[k++] = a[q];
  20.     else
  21.         for(int q = begin2; q <= end2; q++)
  22.             b[k++] = a[q];
  23. }

  24. void MergePass(int a[], int b[], int seg, int size)
  25. {
  26.     int seg_start_ind = 0;
  27.     while(seg_start_ind <= size - 2 * seg)
  28.     {
  29.         Merge(a, b, seg_start_ind, seg_start_ind + seg - 1, seg_start_ind + seg * 2 - 1);
  30.         seg_start_ind += 2 * seg;
  31.     }

  32.     if(seg_start_ind + seg < size)
  33.         Merge(a, b, seg_start_ind, seg_start_ind + seg - 1, size - 1);
  34.     else
  35.         for(int j = seg_start_ind; j < size; j++)
  36.             b[j] = a[j];
  37. }

  38. void MergeSort(int a[], int size)
  39. {
  40.     int* temp = new int[size];
  41.     int seg = 1;
  42.     while(seg < size)
  43.     {
  44.         MergePass(a, temp, seg, size);
  45.         seg += seg;
  46.         MergePass(temp, a, seg, size);
  47.         seg += seg;
  48.     }
  49. }

  50. int main()
  51. {
  52.     int a[] = {3, 5, 3, 6, 4, 7, 5, 7, 4};
  53.     MergeSort(a, sizeof(a) / sizeof(*a));
  54.     //输出
  55.     for(unsigned int i = 0; i < sizeof(a) / sizeof(*a); i++)
  56.         cout << a[i] << ' ';
  57.     cout << endl;

  58.     return 0;
  59. }

阅读(1051) | 评论(0) | 转发(0) |
0

上一篇:如何在Visual Studio 2010下制作DLL并调用

下一篇:没有了

给主人留下些什么吧!~~