Pagini recente » Cod sursa (job #2861033) | Cod sursa (job #1106202) | Cod sursa (job #775170) | Cod sursa (job #2966621) | Cod sursa (job #2192352)
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.PrintWriter;
import java.util.Random;
import java.util.Scanner;
public class Main {
private static Random random = new Random();
private static int[] numbers;
public static void main(String[] args) throws FileNotFoundException {
int order = readInput();
int orderStatistic = find(order);
writeOutput(orderStatistic);
}
public static int readInput() throws FileNotFoundException {
Scanner scanner = new Scanner(new FileReader("sdo.in"));
int n = scanner.nextInt();
int order = scanner.nextInt()-1;
numbers = new int[n];
for (int i=0; i<n; i++) {
numbers[i] = scanner.nextInt();
}
scanner.close();
return order;
}
public static void writeOutput(int orderStatistic) throws FileNotFoundException {
PrintWriter writer = new PrintWriter("sdo.out");
writer.print(orderStatistic);
writer.close();
}
public static int find(int order) {
if (numbers == null || numbers.length == 0) {
throw new IllegalStateException();
}
if (order >= numbers.length) {
throw new IllegalArgumentException();
}
int start = 0;
int end = numbers.length-1;
int pivot;
do {
pivot = partition(start, end);
if (pivot < order) {
start = pivot+1;
}
if (pivot > order) {
end = pivot-1;
}
} while (pivot != order);
return numbers[pivot];
}
private static int partition(int start, int end) {
int rand = random.nextInt(end-start);
swap(start+rand, end);
int lt_eq = start, pivot = numbers[end];
for (int i=start; i<end-1; i++) {
if (numbers[i] <= pivot) {
swap(i, lt_eq++);
}
}
swap(lt_eq, end);
return lt_eq;
}
private static void swap(int a, int b) {
int tmp = numbers[a];
numbers[a] = numbers[b];
numbers[b] = tmp;
}
}