码迷,mamicode.com
首页 > 编程语言 > 详细

归并排序

时间:2015-07-14 22:08:02      阅读:196      评论:0      收藏:0      [点我收藏+]

标签:

算法思想:

技术分享

代码:

 

 1  template <typename Comparable>
 2 void mergeSort(vector<Comparable>&a)
 3 {
 4   mergeSort(a,0,a.size()-1);
 5 }
 6 
 7 template <typename Comparable>
 8 void mergeSort(vector<Comparable>&a,int left, int right)
 9 {
10   if (left < right)
11   {
12     int mid = (left + right)/2;
13     mergeSort(a,left, mid);
14     mergeSort(a,left, mid+1,right);
15   }
16 }
17 
18 template <typename Comparable>
19 void merge (vector<Comparable&a, int leftStart, int rightStart, int rightEnd)
20 {
21   int leftEnd = rightStart - 1;
22   int numElements = rightEnd - leftStart + 1;
23   vector<Comparable>temp(numElements);
24   int indexTemp = 0;
25   int tempLeftStart = leftStart;
26   while ( leftStart <= leftEnd && rightStart <= rightEnd )
27   {
28     if ( a[leftStart] <= a[rightStart] )
29       temp[indexTemp++] = a[leftStart++];
30     else
31       temp[indexTemp++] = a[rightStart++];
32   }
33   while ( leftStart <= leftEnd )
34     temp[indexTemp++] = a[leftStart++];
35   while ( rightStart <= rightEnd )
36     temp[indexTemp++] = a[rightStart++];
37   for ( int i = 0; i < numElements; ++i )
38       a[tempLeftStart + i] = temp[i];
39 }

 

归并排序

标签:

原文地址:http://www.cnblogs.com/happygirl-zjj/p/4646437.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!