求助,为什么我的快速排序老是排不对

P1923 【深基9.例4】求第 k 小的数

notwhy @ 2022-07-15 02:23:02

我都是照着老师的模板写的,不知道为什么老是会有元素被覆盖

#include <stdio.h>
void Qsort(int a[], int low, int high);
int part(int a[], int low, int high);
int main()
{
    int a[10] = {0};
    int n, k;
    scanf("%d %d", &n, &k);
    for(int i = 1; i <= n; i++)
    {
        scanf("%d", &a[i]);
    }
    Qsort(a, 1, n);
    printf("%d", a[k + 1]);
    return 0;
}

void Qsort(int a[], int low, int high)
{
    if(low < high)
    {
        int pivo;
        pivo = part(a, low, high);
        Qsort(a, low, pivo - 1);
        Qsort(a, pivo + 1, high);
    }
}

int part(int a[], int low, int high)
{
    int mid = a[1];
    while (low < high)
    {
        while (low < high && a[high] >= mid)
        {
            high--;
        }
        a[low] = a[high];
        while (low < high && a[low] <= mid)
        {
            low++;
        }
        a[high] = a[low];
    }
    a[low] = mid;
    return low;
}
比如样例这个 4 3 2 1 5
会被排成 1 1 2 4 5

by mzyc_yang2021 @ 2022-07-15 07:22:20

直接用

sort();

不好吗


by KAqwq @ 2022-07-15 07:36:18

@mzyc_yang2021 yysy直接用sort过不了这道


by mzyc_yang2021 @ 2022-07-15 07:38:54

@Kamisato_Ayato 欧,不好意思。


by _czk_ @ 2022-07-15 08:05:42

你可以先对比一下我的代码
#include<bits/stdc++.h>
using namespace std;
int n,m;
int a[5000005];
void quick(int l,int r){
    int i = l,j = r, k = a[(i+j)/2];
    do{
        while(a[j]>k)j--;
        while(a[i]<k)i++;
        if(i <= j){
            swap(a[i],a[j]);
            i++,j--; 
        }
    }while(i<=j);
    if(m<=j) quick(l,j);
    else if(i<=m) quick(i,r);
    else{
        printf("%d",a[m]);
        return;
    }

} 
int main(){
    scanf("%d%d",&n,&m);
    for(int i = 0;i < n;i++)
        scanf("%d",&a[i]);
    quick(0,n-1);
    return 0;
}

by notwhy @ 2022-07-15 11:07:04

@mzyc_yang2021 c语言没法用,hhhhhh,果然c++还是方便


|