算法学习之旅,中级篇(4)-–快速排序

来源:互联网 发布:方块导航网源码 编辑:程序博客网 时间:2024/06/05 20:13

介绍
通过一趟遍历把要排序的数据分割成独立的两部分,其中一部分所有数据比另外的一部分所有数据都小。然后再按此方法对这两部分数据进行快速排序,整个排序过程可以递归进行。
分析
快速排序是找出一个元素作为基准,然后对数组进行分区操作,使基准左边元素的值都不大于基准值,基准右边的元素值都不小于基准值,如此作为基准的位置就确定了。
首先找基准元素,然后递归快排。
代码

#include<stdio.h>#include<iostream>using namespace std;void print(int a[],int n){    for(int j=0;j<n;j++)        cout<<a[j]<<" ";    cout<<endl;    return;}void swap(int *a,int *b){   int temp=*a;   *a=*b;   *b=temp;   return;}int partition(int a[],int low,int high){    //基准元素    int k=a[low];    //从表的两端交替地向中间扫描    int b=a[high];    int c=a[low];     while(low<high)     {//从high所指位置向前搜索,至多到low+1位置,将比基准元素小的交换到低端         while(low<high&&a[high]>k)             --high;         while(a[low]<k)             ++low;         swap(&a[low],&a[high]);          print(a,10);     }     a[low]=a[high];     a[high]=k;     print(a,10);     return low;}void quickSort(int a[],int low,int high){    if(low<high)    {//将表一分为二        int privotLoc=partition(a,low,high);        //递归对低子表递归排序        quickSort(a,low,privotLoc-1);        quickSort(a,privotLoc+1,high);    }    return;}int main(){    int a[10]={3,1,5,7,2,4,9,6,10,8};    cout<<"初始值:";    print(a,10);    quickSort(a,0,9);    cout<<"结果:";    print(a,10);    system("pause");    return 0;}

遇到的问题
习惯性把这个快排的比较移动操作当成插入排序来写T.T

原创粉丝点击