快速排序
快速排序1
void swapa(int &a,int &b){
int t = a;
a = b;
b = t;
}
int par(int a[],int low,int high){
int key;
key = a[low];
while (low < high)
{
while(low<high && a[high]>=key)
{
high--;
}
if (low < high)
{
swapa(a[low],a[high]);
low++;
}
while (low<high && a[low] <= key)
{
low++;
}
if (low < high)
{
swapa(a[low],a[high]);
high--;
}
}
a[low] = key;
return low;
}
void quick(int a[],int low,int high){
if (low < high)
{
int r = par(a,low,high);
//show(a, 8);
//getchar();
quick(a, low, r-1); //对左边排序
quick(a, r+1, high);//再对右边排序
}
}
2
int par2(int a[],int low,int high){
int key;
key = a[low];
while (low < high)
{
while(low<high && a[high]>=key)
{
high--;
}
if (low < high)
{
a[low] = a[high];
low++;
}
while (low<high && a[low] <= key)
{
low++;
}
if (low < high)
{
a[high] = a[low];
high--;
}
}
a[low] = key;
return low;
}
各种快排的选择题
已知关键字序列{66,82,25,51,98,108} ,利用快速排序方法,以第一个元素为基准得到的一趟排序结果为
$表示左指针位置,#表示右指针位置
右指针先找
右边找小于key的,左边找大于key的,找的就交换,对端指针++;
右指针开始轮询,比如右边找到了,左右交换,同时左指针++,右指针保持,接着左指针开始轮询
{66,82,25,51,98,108}
51,$82,25,#66,98,108
51,$66,#25,82,98,108
51,25,#$66,82,98,108
对序列{ 30, 15, 20, 60, 70, 80, 5, 100, 10, 40}进行一次快速排序, 第一次快排后,排序结果为?
以第一个为key
{30,15,20,60,70,80,5,100,10,40}
key=30
10,$15,20,60,70,80,5,100,#30,40
10,15,20,$30,70,80,5,#100,60,40
10,15,20,5,$70,80,#30,100,60,40
10,15,20,5,#$30,80,70,100,60,40