利用快排尋找陣列中第k個最大元素
阿新 • • 發佈:2019-01-14
/* * 利用快排尋找陣列中第k個最大元素 */ public class FindFirstKElement { //快排 public static int getBaseIndex(int[] arr, int start, int end) { int base = arr[start]; while(start < end) { while(arr[end] > base && end > start) { end --; } if(end <= start) { break; } else { int temp = arr[end]; arr[end] = arr[start]; arr[start] = temp; } while(arr[start] < base && start < end) { start ++; } if(start >= end) { break; } else { int temp = arr[start]; arr[start] = arr[end]; arr[end] = temp; } } return start; } public static void findFirstKElement(int[] arr, int k, int start, int end) { int middle = getBaseIndex(arr, start, end); if(middle == k - 1) { System.out.println(arr[middle]); } else if(middle < k - 1) { //middle右邊找 findFirstKElement(arr, k, middle + 1, end); } else { //middle左邊找 findFirstKElement(arr, k, start, middle - 1); } } public static void main(String[] args) { int[] arr = {23,4,6,8,232}; int k = 2; int start = 0; int end = arr.length - 1; findFirstKElement(arr, k, start, end); } }