背模板
C++ 代码
#include<iostream>
using namespace std;
const int N = 1e6 + 10;
int q[N];
void swap_q(int q[], int x, int y)
{
if(x== y) return;
int z = q[x + y >> 1], i = x - 1, j = y + 1;
while(i < j)
{
do i++; while(q[i] < z);
do j--; while(q[j] > z);
if(i < j) swap(q[i], q[j]);
}
swap_q(q, x, j);
swap_q(q, j + 1, y);
}
int main()
{
int n, k;
cin >> n >> k;
for(int i = 0; i < n; i++) cin >> q[i];
swap_q(q, 0 , n - 1);
cout << q[k - 1];
return 0;
}
Java 代码
import java.util.Scanner;
public class Main
{
static int N = 1000010;
static int q[] = new int[N];
public static void main(String[] args)
{
Scanner in = new Scanner(System.in);
int n, k;
n = in.nextInt();
k = in.nextInt();
for(int i = 0; i < n; i++) q[i] = in.nextInt();
swap_a(q, 0, n - 1);
System.out.println(q[k - 1]);
}
public static void swap_a(int q[], int x, int y)
{
if(x == y) return;
int z = q[(x + y) / 2], i = x - 1, j = y + 1;
while(i < j)
{
do i++; while(q[i] < z);
do j--; while(q[j] > z);
if(i < j)
{
q[i] = q[i] + q[j];
q[j] = q[i] - q[j];
q[i] = q[i] - q[j];
}
}
swap_a(q, x, j);
swap_a(q, j + 1, y);
}
}