图片来自MOOC
归并排序代码
#include <iostream>
using namespace std;
const int maxn = 10;
void Merge(int a[],int s,int m,int e,int temp[])
{
int p1,p2,k;
p1 = s;
p2 = m+1;
k = 0;
while(p1 <= m && p2 <= e) {
if(a[p1] < a[p2])
temp[k++] = a[p1++];
else
temp[k++] = a[p2++];
}
while(p1 <= m)
temp[k++] = a[p1++];
while(p2 <= e)
temp[k++] = a[p2++];
for(int i=0;i<k;i++)
a[s++] = temp[i];
}
void MergeSort(int a[],int s,int e,int temp[]) // start end
{
if(s < e) {
int mid = s+(e-s)/2;
MergeSort(a,s,mid,temp);
MergeSort(a,mid+1,e,temp);
Merge(a,s,mid,e,temp);
}
}
int main()
{
int a[maxn] = {1,8,9,20,0,2,6,34,9,8};
int temp[maxn];
MergeSort(a,0,maxn-1,temp);
for(int i=0;i<maxn;i++)
cout << a[i] << " ";
cout << endl;
}
快速排序代码
时间复杂度O (N*log N),c/c++库里的sort()就是用的快速排序
#include <iostream>
using namespace std;
const int maxn = 10;
void swap(int &a,int &b)
{
int c = a;
a = b;
b = c;
}
void QuickSort(int a[],int l,int r)
{
if(l > r)
return;
int i,j;
i = l;
j = r;
int temp = a[l];
while(i != j) {
while(a[j] >= temp && i<j) // 一定要从先右边开始走
j--;
while(a[i] <= temp && i<j)
i++;
swap(a[i],a[j]);
}
swap(a[l],a[i]);
QuickSort(a,l,i-1);
QuickSort(a,i+1,r);
}
int main()
{
int a[maxn] = {1,8,9,20,0,2,6,34,9,8};
QuickSort(a,0,maxn-1);
for(int i=0;i<maxn;i++)
cout << a[i] << " ";
cout << endl;
}