快排、归并与堆排模版

快排

void quick_sort(int q[], int l, int r) {
    if (l >= r) return;
    int i = l - 1, j = r + 1, x = q[l + r >> 1];
    while (i < j) {
        do i++; while (q[i] < x);
        do j--; while (q[j] > x);
        if (i < j) swap (q[i], q[j]);
    }
    quick_sort(q, l, j), quick_sort(q, j + 1, r);
}

https://www.acwing.com/problem/content/787/

快排详解:https://blog.csdn.net/u013570834/article/details/106183702

归并

void merge_sort(int q[], int l, int r) {
    if (l >= r) return;
    int m = l + r >> 1, i = l, j = m + 1, k = 0;
    merge_sort(q, l, m), merge_sort(q, m + 1, r);
    while (i <= m && j <= r) tmp[k++] = q[i] < q[j] ? q[i++]:q[j++];
    while (i <= m) tmp[k++] = q[i++];
    while (j <= r) tmp[k++] = q[j++];
    for (i = l, j = 0; i <= r; i++, j++) q[i] = tmp[j];
}

https://www.acwing.com/problem/content/789/

归并详解 https://blog.csdn.net/u013570834/article/details/106165046

堆排

void down(int u) {
    int t = u;
    if (2 * u <= h[0] && h[t] > h[2 * u]) t = 2 * u;
    if (2 * u + 1 <= h[0] && h[t] > h[2 * u + 1]) t = 2 * u + 1;
    if (u != t) {
        swap(h[u], h[t]);
        down(t);
    }
}

void heap_sort(int a[], int n) {
    for (int i = 1; i <= n; i++) h[i] = a[i - 1];
    h[0] = n;
    for (int i = n / 2; i; i--) down(i);
    for (int i = 0; i < n; i++) {
        a[i] = h[1];
        h[1] = h[h[0]--];
        down(1);
    }
}

https://www.acwing.com/problem/content/description/840/

多敲多练,方能倒背如流

参考资料

Acwing

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值