本代码实质上是对取首位元素作为快速的排序的小改动。
同时注意,本代码定义的数据类型为double类型,如果将之更换为int类型,则由于int类型在计算平均值时,计算出的数还是int,可能会引发不能退出递归的错误。
代码如下:
# include<iostream>
using namespace std;
int partition(double a[], int low, int high)
{
double avg, sum = 0;
for(int i = low; i <= high; i++)
sum += a[i];
avg = sum / (high - low + 1);
double pivot = a[low];
while(low < high){
while(low < high && a[high] >= avg)
high --;
a[low] = a[high];
while(low < high && a[low] <= avg)
low ++;
a[high] = a[low];
}
a[low] = pivot;
if(pivot <= avg)
return low;
else
return low - 1;
}
void quicksort(double a[], int low, int high)
{
if(low < high)
{
cout << "low " << low << " high " << high << endl;
cout << a[low] << " " << a[high] << endl;
int k = partition(a, low, high);
quicksort(a, low, k);
quicksort(a, k + 1, high);
}
}
int main()
{
int n = 8;
double a[] = {8, 7, 5, 13, 29, 18, 6, 4};
quicksort(a, 0, n - 1);
for(int i = 0; i < n; i++)
cout << a[i] << " ";
cout << endl;
return 0;
}