shenshen1999 @ 2024-04-04 12:16:52
代码如下
#include<stdio.h>
#include<stdlib.h>
#define Cutoff 3
void swap(long long* a, long long* b)
{
long long temp;
temp = *a;
*a = *b;
*b = temp;
}
void sort(long long arr[], int n)
{
int i, j;
for (i = 1;i < n;i++)
{
long long temp = arr[i];
for (j = i;j > 0 && arr[j - 1] > temp;j--)
{
arr[j] = arr[j - 1];
}
arr[j] = temp;
}
}
long long Median3(long long a[], int left, int right)
{
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]);
if (a[center] > a[right])
swap(&a[center], &a[right]);
swap(&a[center], &a[right - 1]);
return a[right - 1];
}
long long quicksort1(long long a[], int left, int right,int k)//
{
int i, j;
long long pivot;
if (left + Cutoff <= 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 (i == k)
return a[i];
if(i<k)
return quicksort1(a, i + 1, right,k);
else if(i>k)
return quicksort1(a, left, i - 1,k);
}
else
sort(a, right - left + 1);
return a[k];
}
int main()
{
long long a[5000000] = { 0 };
int n, k;
scanf("%d %d", &n, &k);
for (int i = 0;i < n;i++)
{
scanf("%lld", &a[i]);
}
printf("%lld", quicksort1(a, 0, n - 1,k));
return 0;
}
用的三分中值取快排的枢纽元并且递归时筛选k所在位置,不可取时用插入排序排序返回第K小的数字 仅有第五个测试集WA,错误信息如下 Wrong Answer.wrong answer On line 1 column 6, read 0, expected 1.
by __little__Cabbage__ @ 2024-04-04 13:00:53
建议用STL