1. 程式人生 > 其它 >java學習筆記(六)

java學習筆記(六)

技術標籤:Java學習

java學習筆記(六)

演算法部分:

尋找第K大的數字

​ 有一個整數陣列,請你根據快速排序的思路,找出陣列中第K大的數。

給定一個整數陣列a,同時給定它的大小n和要找的K(K在1到n之間),請返回第K大的數,保證答案存在。

在快排的基礎上,只排序該數字可能在的一邊,另一個邊不排序,就可以減少一半的時間.
import java.util.*;

public class Finder {
        public static int quickSort(int[] arr,int low,int high , int K){
        int i,
j,temp; i=low; j=high; temp = arr[low]; while (i<j) { while (temp>=arr[j] && i<j) { j--; } while (temp<=arr[i] && i<j) { i++; } if (i<j) { int
z = arr[i]; arr[i] = arr[j]; arr[j] = z; } } arr[low] = arr[i]; arr[i] = temp; if ((i-low +1)==K){ return arr[i]; } else if ((i-low+1)>K){ temp=quickSort(arr,low,i-1,K); }
else { temp=quickSort(arr,i+1,high,K-(i-low+1)); } return temp; } public int findKth(int[] a, int n, int K) { int temp=quickSort(a,0,n-1,K); return temp; } }