快速排序算法
笔记:
#include<iostream>
#include<string.h>
using namespace std;
void quite_sort(int *a,int low,int high);
int partitions(int *a,int low, int high);
int main()
{
int a[201];
int n;
memset(a,0,sizeof(a));
cin >> n;
int i;
for(i = 0;i < n; i++)
{
cin >> a[i];
}
quite_sort(a,0,n - 1);
for(i = 0;i < n; i++)
{
cout << a[i] << " ";
}
}
int partitions(int *a,int low, int high)
{
int p = a[low];
while(low < high)
{
while(a[high] >= p && low < high)//注意这里的a[high] >= p和下面的a[low] < p一定要形成闭区间,就是一个有等号一个没有等号
{ //为什么外面已经有一个while low < high了里面还要写一个,能不能省略?不能,因为里面的i和j双向在变化,可能满足外部条件但是到了循环内部变化一次就不循环了,此时low,high就不应该再做运算了
high --;
}
if(low >= high)
{
break;
}
else
a[low] = a[high];//一定要先吧a[low]覆盖,因为a[low]的值已经存储了
while(a[low] < p && low < high)
{
low ++;
}
if(low >= high)
{
break;
}
else
a[high] = a[low];
}
a[low] = p;
return low;
}
void quite_sort(int *a,int low,int high)
{
if(low < high)//快排永恒的条件,递归就不用循环了,所以这里是if不是while
{
int p = partitions(a,low,high);
quite_sort(a,low,p - 1);
quite_sort(a,p + 1,high);
}
}