C++实现快速排序

来源:互联网 发布:列克星敦战巡数据 编辑:程序博客网 时间:2024/06/06 06:58

2》C++实现

#include<iostream>using namespace std;#define ARRAY_SIZE 8+1//有一个位置是枢轴记录/*description:在标准输出设备上显示数组元素。parameter:int* p:指向整形数组首元素的指针int length:整形数据长度*/void myshow(int*  p,int length){for(int i=0;i<length;i++){cout<<*(p+i)<<"\t";}cout<<endl;}/*以low位置的元素为枢轴划分表[low ... high]*/int partition(int * p_start,int low,int high){p_start[0]=p_start[low];//用子表的第一个记录作枢轴记录while(low < high){//从表的两端交替地向中间扫描while(low < high && p_start[high] >= p_start[0]){high--;}p_start[low]=p_start[high];//将比枢轴记录小的记录移到低端while(low < high && p_start[low] <= p_start[0]){low++;}p_start[high]=p_start[low];//将比枢轴记录大的记录移到高端}p_start[low]=p_start[0];//枢轴记录到位return low;//返回枢轴位置 }void quickSort(int *p,int low,int high){//对顺序表中的子序列[low ... high]作快速排序if(low<high){//长度大于1int pivot_loc= partition(p,low,high);quickSort(p,low,pivot_loc-1);//对低子表递归排序,pivot_loc是枢轴位置quickSort(p,pivot_loc+1,high);//对高子表递归排序,pivot_loc是枢轴位置}}int main(){void myshow(int*  p,int length);//函数提前声明int list[ARRAY_SIZE]={-1,49,38,65,97,76,13,27,49};//位置0是哨兵cout<<"排序前:"<<endl;myshow(list,ARRAY_SIZE);quickSort(list,1,ARRAY_SIZE-1);//真正要排序的数据从位置[1]到[ARRAR_SIZE-1],位置[0]为辅助空间cout<<"排序后:"<<endl;myshow(list,ARRAY_SIZE);return 0;}

运行结果:

3》时间及空间复杂度分析



0 0