您的位置:首页 > 其它

快速排序

2015-09-26 22:42 246 查看
#include<cstdio>

#include<ctime>

#include<cstdlib>

=====================================================

void Swap(int& a,int& b){

if(a!=b){

a^=b;b^=a;a^=b;

}

}

=====================================================

int Partition(int *A,int p,int r)

{

int x,i;

x=A[r];

i=p-1;

for(int j=p;j<=r-1;++j)

{

if(A[j]<=x)

i++;//x为最后一个数,小于x, 不动(交换)本身(未有大于x的)

Swap(A[i],A[j]);

}

Swap(A[++i],A[r]);

return i;

}

//已有大于x的时,再遇小于x:交换

//i为最后一个小于等于x元素的下标。

=====================================================

void QuickSort(int *A,int p,int r)

{

if(p<r)

{

int q = Partition(A,p,r);

QuickSort(A,p,q-1);

QuickSort(A,q+1,r);

}

}

#include<cstdio>

#include<ctime>

#include<cstdlib>

inline void Swap(int &a, int &b)

{

if(a!=b)

{

a^=b;

b^=a;

a^=b;

}

}

int Partition(int *A,int front,int end)

{

int key = A[end];

int i = front - 1;

for(int current = front;current < end;++current)

{

if(A[current]<=key)

Swap(A[++i],A[current]);

}

Swap(A[++i],A[end]);

return i;

}

void QuickSort (int *A,int front,int end)

{

if(front < end)

{

int midPosition = Partition(A,front,end);

QuickSort(A,front,midPosition-1);

QuickSort(A,midPosition+1,end);

}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: