有没有大佬能帮我看一下我的快选代码哪里出了问题啊?第三个测试点一直WA

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

lididas @ 2022-11-11 14:46:06

#include <stdio.h>
#include <stdlib.h>

/*利用快选解决选择问题*/

void InsertionSort(unsigned int A[],unsigned int N)
{
    unsigned int j,P;

    unsigned int Tmp;
    for(P = 1;P < N;P++)
    {
        Tmp = A[P];
        for(j = P;j > 0 && A[j-1] > Tmp;j--)
            A[j] = A[j-1];
        A[j] = Tmp;
    }
}

void Swap(unsigned int* a,unsigned int* b)
{
    unsigned int tmp;
    tmp = *a;
    *a = *b;
    *b = tmp;
}

unsigned int Median3(unsigned int A[],unsigned int Left,unsigned int Right)
{
    unsigned int Center = (Left + Right) / 2;

    if(A[Left] > A[Center])
        Swap(&A[Left],&A[Center]);
    if(A[Left] > A[Right])
        Swap(&A[Left],&A[Right]);
    /* A[Left] < A[Center] && A[Left] < A[Right]*/
    if(A[Center] > A[Right])
        Swap(&A[Center],&A[Right]);

    Swap(&A[Center],&A[Right - 1]);

    return A[Right - 1];
}

void Qselect(unsigned int A[],unsigned int k,unsigned int Left,unsigned int Right)
{
    unsigned int i,j;
    unsigned int Pivot;

    if((Left + 3) <= Right)
    {
        Pivot = Median3(A,Left,Right);
        i = Left;j = Right - 1;
        for(;;)
        {
            while(A[++i] < Pivot){};
            while(A[--j] > Pivot){};

            if(i < j)
                Swap(&A[i],&A[j]);
            else
                break;
        }
        Swap(&A[i],&A[Right - 1]);

        if(k <= i)
            Qselect(A,k,Left,i - 1);
        else if(k > i + 1)
            Qselect(A,k,i + 1,Right);
    }
    else
        InsertionSort(A+Left,Right - Left + 1);
}

int main()
{
    unsigned int n,i,k;
    unsigned int* A;

    scanf("%d",&n);
    scanf("%d",&k);

    A = (unsigned int*)malloc(sizeof(unsigned int) * n);

    for(i = 0;i < n;i++)
        scanf("%d",&A[i]);

    Qselect(A,k,0,n-1);

    printf("%d",A[k]);

    return 0;
}

by Zhangyanlin @ 2022-11-11 22:58:29

麻烦说一下你的思路或者加上解释,直接看程序不太好理解


|