快速排序模板 C++ and python

#include <iostream>
#include <cstdio>
#include <algorithm>

using namespace std;
const int N = 1e5 + 5;

int a[N];

void quick_sort(int q[], int l, int r)
{
    if(l >= r)
        return ;

    int x = q[l + r >> 1], i = l - 1, j = 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);
    return ;
}
int main()
{
    int n;
    scanf("%d", &n);
    for(int i = 0; i < n; ++ i)
        scanf("%d", &a[i]);
    quick_sort(a, 0, n - 1);
    for(int i = 0; i < n; ++ i)
        printf("%d ", a[i]);
    return 0;
}
def quick_sort(q, L, R):
    if L >= R:
        return
    x = q[L + R >> 1]
    i = L - 1
    j = R + 1
    while i < j:
        i += 1
        while q[i] < x:
            i += 1
        j -= 1
        while q[j] > x:
            j -= 1  #==
        if i < j:
            temp = q[i]
            q[i] = q[j]
            q[j] = temp
    quick_sort(q, L, j)
    quick_sort(q, j + 1, R)
    return


n = int(input())
a = list(map(int, input().split()))

quick_sort(a, 0, n - 1)

for i in range(n):
    print(a[i], end=" ")

https://www.acwing.com/problem/content/description/787/测试通过

猜你喜欢

转载自www.cnblogs.com/Chaosliang/p/12177992.html