快速排序法!

王朝other·作者佚名  2008-06-01
窄屏简体版  字體: |||超大  

/// E-mail:cangzhu@163.com

//快速排序法

//基本的思想:通过一趟排序将待排的记录分割成独立的两部分,

//其中前一部分的 记录的要害字均比另一部分记录的要害字小,

//再分别对两组记录进行递归分割,达到排序的目的

//平均时间复杂度为 O(log2(n))

#include "iostream.h"

#include "stdlib.h"

//交换两变量值

void swap(int &a,int &b)

{

int c;

c=a;a=b;b=c;

}

//将数组分成两部分,前一部分的值均比后一部分值小

//返回分界点

int Partition(int data[],int low,int high)

{

int pivokey;

pivokey=data[low];

while(low<high)

{

while(low<high&&data[high]>=pivokey)

high--;

swap(data[low],data[high]);

while(low<high&&data[low]<=pivokey)

low++;

swap(data[low],data[high]);

}

return low;

}

//进行的递归的调用,达到排序的目的

void QSort(int data[],int low,int high)

{

if(low<high)

{

int pivokey=Partition(data,low,high);

QSort(data,low,pivokey-1);

QSort(data,pivokey+1,high);

}

}

void main()

{

int i;

int mydata[50];

for(i=0;i<50;i++)

{

//每行显示 10 个数据

if(i%10==0)

cout<<endl;

mydata[i]=rand()%100;

cout<<mydata[i]<<" ";

}

QSort(mydata,0,49);

cout<<endl<<endl;

for(i=0;i<50;i++)

{

//每行显示 10 个数据

if(i%10==0)

cout<<endl;

cout<<mydata[i]<<" ";

}

}

 
 
 
免责声明:本文为网络用户发布,其观点仅代表作者个人观点,与本站无关,本站仅提供信息存储服务。文中陈述内容未经本站证实,其真实性、完整性、及时性本站不作任何保证或承诺,请读者仅作参考,并请自行核实相关内容。
 
 
© 2005- 王朝網路 版權所有 導航