您的位置:首页 > 其它

花了好长一段时间,终于把快速排序法弄懂了。

2010-04-24 10:44 218 查看
//快速排序法

#include<iostream>

using namespace std;

void split(int a[],int low,int high,int &i)

{//a[]为2 8 3 6 9 5 1 4 0 7

i=low;

int j=high;

int x=a[i];

while(i<j)

{

//目标:x=2, a[]=2 8 3 6 9 5 1 4 0 7

//=>x=2, a[]=0 1 2 6 9 5 3 4 8 7

while(x<=a[j] && i<j)

j--;

if(i<j)

{

a[i]=a[j];

i++;

}

while(x>a[i] && i<j)

i++;

if(i<j)

{

a[j]=a[i];

j--;

}

}

a[i]=x;

}

void qsort(int a[],int s,int t)

{

int i;

if(s<t)

{

split(a,s,t,i);

qsort(a,0,i-1);

qsort(a,i+1,t);

// cout<<a[i]<<" ";

}

}

void qsort1(int a[],int n)

{

qsort(a,0,n-1);

}

void qsort2(int a[],int n)

{

int stack[100][2];

int i;

int j,k;

int top=0;

stack[top][0]=0;

stack[top][1]=n-1;

while(top>=0)

{

j=stack[top][0];

k=stack[top][1];

top--;

split(a,j,k,i);

if(j<k)

{

top++;

stack[top][0]=j;

stack[top][1]=i-1;

top++;

stack[top][0]=i+1;

stack[top][1]=k;

}

}

cout<<endl;

}

void display(int a[],int n)

{

for(int i=0;i<n;i++)

{

cout<<a[i]<<" ";

}

}

int main()

{

int a[]={2,8,3,6,9,5,1,4,0,7};

int n=10;

// int i;

qsort1(a,n);

// display(a,n);

// cout<<endl;

// split(a,0,n-1,i);

// cout<<endl;

display(a,n);

qsort2(a,n);

display(a,n);

return 0;

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