您的位置:首页 > 其它

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

2017-08-23 22:41 267 查看
介绍

通过一趟遍历把要排序的数据分割成独立的两部分,其中一部分所有数据比另外的一部分所有数据都小。然后再按此方法对这两部分数据进行快速排序,整个排序过程可以递归进行。

分析

快速排序是找出一个元素作为基准,然后对数组进行分区操作,使基准左边元素的值都不大于基准值,基准右边的元素值都不小于基准值,如此作为基准的位置就确定了。

首先找基准元素,然后递归快排。

代码

#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
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息