快速排序算法
百科名片
A[0] | A[1] | A[2] | A[3] | A[4] | A[5] | A[6] |
49 | 38 | 65 | 97 | 76 | 13 | 27 |
。
#include <iostream>
#include <algorithm>
using namespace std;
const int size = 1000;
//第一种写法
int partition1(int a[], int low, int high)
{
int p = a[low];
while (low < high)
{
while (low < high && p <= a[high]) high--;//右边的与p比较,若右边的大于它继续往左走
a[low] = a[high];//遇到a[low] > a[high]了,while结束,交换p和a[high];
while (low < high && a[low] <= p) low++;
a[high] = a[low];
}
a[low] = p;
return low;
}
//第2种写法
int partition2(int a[], int low, int high)
{
//选择第一个a[low]作为划分的临界值
while (low < high)
{
while (low < high && a[low] <= a[high]) high--;
swap(a[low], a[high]);
while (low < high && a[low] <= a[high]) low++;
swap(a[low], a[high]);
}
return low;
}
void Qsort(int a[], int low, int high)
{
if (low > high) return;
int p = partition2(a, low, high);
Qsort(a, low, p-1);
Qsort(a, p+1, high);
}
int main()
{
int N, arr[size];
int i;
while (cin >> N)
{
for (i = 0; i < N; ++i)
cin >> arr[i];
Qsort(arr, 0, N-1);
for (i = 0; i < N-1; ++i)
cout << arr[i] << " ";
cout << arr[i] << endl;
}
return 0;
}
快排题目 : hdu 1157 4022 二分+快排 1040 1425 1106
2037 贪心结构体快排