C++平均值作为轴枢进行快速排序

本代码实质上是对取首位元素作为快速的排序的小改动。
同时注意,本代码定义的数据类型为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;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值