1
#include <stdio.h>
2
#include <algorithm>
3
using namespace std;
4
#define MAX 1000
5
int buf[MAX];
6
void merge(int a[],int l,int m,int r)
7![](http://www.cppblog.com/Images/OutliningIndicators/ExpandedBlockStart.gif)
![](http://www.cppblog.com/Images/OutliningIndicators/ContractedBlock.gif)
{
8
int pa=l;
9
int pb=m+1;
10
int k=0;
11![](http://www.cppblog.com/Images/OutliningIndicators/InBlock.gif)
12
while(pa<=m && pb<=r)
13![](http://www.cppblog.com/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
{
14
if(a[pa]<a[pb])
15
buf[k++]=a[pa++];
16
else
17
buf[k++]=a[pb++];
18
}
19
while(pa<=m)
20
buf[k++]=a[pa++];
21
while(pb<=r)
22
buf[k++]=a[pb++];
23![](http://www.cppblog.com/Images/OutliningIndicators/InBlock.gif)
24
for(int i=0;i<k;i++)
25
a[l+i]=buf[i];
26
}
27
void mergeSort(int a[],int l,int h)
28![](http://www.cppblog.com/Images/OutliningIndicators/ExpandedBlockStart.gif)
![](http://www.cppblog.com/Images/OutliningIndicators/ContractedBlock.gif)
{
29
if(l<h)
30![](http://www.cppblog.com/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
{
31
int m=(l+h)/2;
32
mergeSort(a,l,m);
33
mergeSort(a,m+1,h);
34
merge(a,l,m,h);
35
}
36
}
37
void printIntArr(int n)
38![](http://www.cppblog.com/Images/OutliningIndicators/ExpandedBlockStart.gif)
![](http://www.cppblog.com/Images/OutliningIndicators/ContractedBlock.gif)
{
39
printf("%d ",n);
40
}
41
int main()
42![](http://www.cppblog.com/Images/OutliningIndicators/ExpandedBlockStart.gif)
![](http://www.cppblog.com/Images/OutliningIndicators/ContractedBlock.gif)
{
43![](http://www.cppblog.com/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
int a[10]=
{2,89,-1,8,0,7,13,0,11,3};
44
mergeSort(a,0,9);
45
//merge(a,0,4,9);
46
std::for_each(a,a+10,printIntArr);
47
return 0;
48
}
posted on 2010-10-01 22:42
乔宁博 阅读(1727)
评论(2) 编辑 收藏 引用