快速排序问题
要求改写快速排序算法,使得能输出每一趟快排后的结果。
在快速排序中,记录的比较和交换是从两端向中间进行的,关键字较大的记录一次就能交换到后面单元,关键字较小的记录一次就能交换到前面单元,记录每次移动的距离较大,因而总的比较和移动次数较少。
#include <iostream>
using namespace std;
typedef int Type;
int t;
void Swap(int& a, int& b)
{
int temp = a; a = b; b = temp;
}
int Partition(Type a[], int p, int r)
{
int i = p, j = r + 1;
Type x = a[p];
// 将< x的元素交换到左边区域
// 将> x的元素交换到右边区域
while (true) {
while (a[++i] < x); //先做 i=i+1; 再做 a[i]<x;
while (a[--j] > x);
if (i >= j) break;
Swap(a[i], a[j]);
}
a[p] = a[j];
a[j] = x;
t++;
c