算法之快速排序

        快速排序的基本思想是在待排序的n个元素中任取一个元素(通常取第一个元素)作为基准,把该元素放入最终位置后,整个数据序列被基准分割成两个子序列,所有小于基准的元素放在前子序列中,所有大于基准的元素放置在后子序列中,并把基准排在这两个子序列的中间,这个过程称为划分。然后对两个子序列分别重复上述过程,直到每个子序列内只有一个元素或空为止。

#include <iostream>
using namespace std;

void disp(int a[], int n) {
    int i;
    for (i = 0; i < n; i++) {
        cout << a[i] << '\t';
    }
    cout << endl;
}

int Parition(int a[], int s, int t) {
    int i = s, j = t, c;
    int tmp = a[s];
    while (i != j) {
        while (j > i && a[j] >= tmp)
            j--;
        c = a[i];
        a[i] = a[j];
        a[j] = c;
        while (i < j && a[i] <= tmp)
            i++;
        c = a[j];
        a[j] = a[i];
        a[i] = c;
    }
    return i;
}

void QuickSort(int a[], int s, int t) {
    if (s < t) {
        int i = Parition(a, s, t);
        QuickSort(a, s, i - 1);
        QuickSort(a, i + 1, t);
    }
}
int main() {
    int n = 10;
    int a[] = { 3, 1, 5, 8, 10, 9, 6, 4, 2, 7 };
    cout << "排序前" << endl;
    disp(a, n);
    QuickSort(a, 0, n - 1);
    cout << "排序后" << endl;
    disp(a, n);
    return 0;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值