问题描述
- 从长度为n的整型数组x中选择第k小元素,假设x中无重复元素。
解决方法
方法一
- 对数组排序,然后得到第K小元素。时间复杂度O(nlogn)。
- 具体实现如下:
/**
* 快速排序后,选出第K小元素
* @param x 长度为n+1的整型数组,x[0]不用
* @param K 1<=K<=n
* @return 第K小元素值
*/
public static int selectK(int [] x,int K)
{
sort(x, 1, x.length-1);//x下标从1开始
return x[K];
}
/**
* 对数组下标lo...hi之间的元素进行快速排序
* @param x 待排序数组
* @param lo 最低位
* @param hi 最高位
*/
public static void sort(int[] x,int lo,int hi){
if(hi<=lo)return;
int j=partition(x,lo,hi);
sort(x,lo,j-1);
sort(x,j+1,hi);
}
/**
* 一次划分
* @param x 待排序数组
* @param lo 最低位