一、问题描写叙述
给定一个整数数列,寻找其按递增排序后的第k个位置上的元素。
二、问题分析
借助类似快排思想实现pation函数。再利用递归思想寻找k位置。
三、算法代码
public static int selectMinK(int [] arr, int low, int high, int k){ int index = pation(arr, low, high); if(index == k){ return arr[index]; } if(index < k){ return selectMinK(arr, index + 1, high, k); }else{ return selectMinK(arr, low, index - 1, k); } } public static int pation(int [] arr, int low, int high){ while(low < high){ while(low < high && arr[low] <= arr[high]){//从后往前。把小的元素往前调换 high--; } if(low < high){ int tmp = arr[low]; arr[low] = arr[high]; arr[high] = tmp; low++; } while(low < high && arr[low] <= arr[high]){//从前往后。把大的元素往后调换 low++; } if(low < high){ int tmp = arr[low]; arr[low] = arr[high]; arr[high] = tmp; high--; } } return low;//返回low。high相遇位置 }四、完整測试代码
public class Solution { public static void main(String [] args){ int [] randArr = new int[]{5,2,8,6,3,6,9,7}; int result = selectMinK(randArr, 0, randArr.length - 1, 4); System.out.print(result); } public static int selectMinK(int [] arr, int low, int high, int k){ int index = pation(arr, low, high); if(index == k){ //若返回的下标为k,则找到目标元素 return arr[index]; } if(index < k){ return selectMinK(arr, index + 1, high, k); }else{ return selectMinK(arr, low, index - 1, k); } } public static int pation(int [] arr, int low, int high){ while(low < high){ while(low < high && arr[low] <= arr[high]){ high--; } if(low < high){ int tmp = arr[low]; arr[low] = arr[high]; arr[high] = tmp; low++; } while(low < high && arr[low] <= arr[high]){ low++; } if(low < high){ int tmp = arr[low]; arr[low] = arr[high]; arr[high] = tmp; high--; } } return low; } }五、执行结果
第4小元素为:6