【西交ACM】298 第N大的数

【西交ACM】298   第N大的数

http://202.117.21.117/xjoj/problem_html/298.html

Description

一个简单问题,在一串数中找出第N大的数

Input

包含多组数据,第一行输入数据的组数T(<100);每组数据包含2行,第一行2个数N,K,N表示这组数据中一共有N个数,K表示要找的是第K大的数,1<=K<=N<=100;第二行就是N个数(0 - 1000)。

Output

一共T行,每行输出该组数据的第K大数。

Sample Input

2
4 2
1 2 8 7
7 5
87 136 769 178 85 55 974

Sample Output

7
87

使用快速排序,输出指定项就可以了。
 1 //author:pz
 2 
 3 import java.util.Scanner;
 4 
 5 public class Main{
 6     public static void main(String[] args) {
 7         //int[] arr = {1,4,7,2,5,8,3,6,9};
 8         Scanner sc =new Scanner(System.in);
 9         int t = sc.nextInt();
10         for(int i = 0; i < t;  i ++){
11             int n = sc.nextInt();
12             int k = sc.nextInt();
13             int[] arr = new int[100];
14             for(int j = 0; j < n; j ++){
15                 arr[j] = sc.nextInt();
16             }
17         quickSort(arr);
18      //   printArray(arr);
19         System.out.println(arr[arr.length - k]);
20         }
21         
22     }
23     
24         public static void printArray(int[] array){
25               System.out.println("arr: ");
26               for(int i : array){
27                  System.out.print(i + ", ");
28               } 
29               System.out.println();
30     }
31         
32     public static void quickSort(int[] a) {
33         quickSort(a, 0, a.length - 1);
34     }
35      
36     private static void quickSort(int[] a, int start, int end) {
37             int left = start;
38             int right = end - 1;
39             int pivot = a[end];
40             
41             while (left < right) {
42                 if (a[left] <= pivot) {
43                     left++;
44                     continue;
45                 }
46                 if (a[right] > pivot) {
47                     right--;
48                     continue;
49                 }
50                 swap(a, left++, right);
51             }
52 
53             if (a[left] < pivot) {
54                 left++;
55             }
56             swap(a, left, end);
57 
58       if(left - 1 > start) {
59              quickSort(a, start, left - 1);
60             }
61             if(left + 1 < end) {
62              quickSort(a, left + 1, end);
63             }   
64     }
65 
66     private static void swap(int[] a, int i, int right) {
67         // TODO Auto-generated method stub
68         int temp = a[i];
69         a[i] = a[right];
70         a[right] = temp;
71     }
72 }
原文地址:https://www.cnblogs.com/pengzheng/p/3027746.html