题目描述
输入 n n n( 1 ≤ n < 5000000 1 \le n < 5000000 1≤n<5000000 且 n n n 为奇数)个数字 a i a_i ai( 1 ≤ a i < 10 9 1 \le a_i < {10}^9 1≤ai<109),输出这些数字的第 k k k 小的数。最小的数是第 0 0 0 小。
请尽量不要使用 nth_element
来写本题,因为本题的重点在于练习分治算法。
输入格式
输出格式
样例 #1
样例输入 #1
5 1
4 3 2 1 5
样例输出 #1
2
解析
一、主要思路
使用快速排序。划分枢纽时,若k处于枢纽左边,则左边再次快排;若处在右边,则右边快排,这样无需全部排序。
快排的核心代码如下:
int partition(int low, int high){
int pivot = a[low];
while(low < high){
while(low < high && a[high] >= pivot){
high --;
}
a[low] = a[high];
while(low < high && a[low] <= pivot){
low ++;
}
a[high] = a[low];
}
a[low] = pivot;
return low;
}
void quicksort(int low, int high){
if(low < high){
int pivotpos = partition(low, high);
if(k < pivotpos){
quicksort(low, pivotpos-1);
}
else if (k > pivotpos){
quicksort(pivotpos+1, high);
}
}
}
二、代码
#include <iostream>
using namespace std;
int a[5000005] = {0};
int k = 0;
int partition(int low, int high){
int pivot = a[low];
while(low < high){
while(low < high && a[high] >= pivot){
high --;
}
a[low] = a[high];
while(low < high && a[low] <= pivot){
low ++;
}
a[high] = a[low];
}
a[low] = pivot;
return low;
}
void quicksort(int low, int high){
if(low < high){
int pivotpos = partition(low, high);
if(k < pivotpos){
quicksort(low, pivotpos-1);
}
else if (k > pivotpos){
quicksort(pivotpos+1, high);
}
}
}
int main(){
int n;
scanf("%d", &n);
scanf("%d", &k);
for(int i = 0; i < n; i ++){
scanf("%d", &a[i]);
}
quicksort(0, n-1);
cout << a[k];
}
三、注意点
不能用cin输入,否则最后一个测试点会超时,只能拿到80分。