寻找第K大的数(快速排序的应用)
2024-10-19 11:49:30
有一个整数数组,请你根据快速排序的思路,找出数组中第K大的数。
给定一个整数数组a,同时给定它的大小n和要找的K(K在1到n之间),请返回第K大的数,保证答案存在。
测试样例:
[1,3,5,2,2],5,3
http://blog.csdn.net/hymanxq/article/details/51026818
public class 寻找第K大的数 { public static void main(String[] args) {
// TODO Auto-generated method stub
int[] a = { , , , , }; System.out.println(findKth(a, a.length, ));
/*
* qsort(a, 0, a.length-1); for(int i:a){ System.out.print(i+" "); }
*/
} public static int findKth(int[] a, int n, int K) {
// write code here return qs(a, , a.length - , a.length - K); // 第K大数 的下标
} static void qsort(int[] a, int left, int right) {
if (left < right) {
int p = partition(a, left, right);
qsort(a, left, p - );
qsort(a, p + , right);
}
} static int qs(int[] a, int left, int right, int k) {
// if (left < right)
{
int p = partition(a, left, right);
if (p == k) {
return a[p];
} else if (p > k)
return qs(a, left, p - , k);
else
return qs(a, p + , right, k);
}
} static int partition(int[] a, int left, int right) {
int p = a[left]; while (left < right) {
while (left < right && a[right] >= p) {
right--;
}
if (left < right) {
a[left++] = a[right];
} while (left < right && a[left] <= p) {
left++;
}
if (left < right) {
a[right--] = a[left];
}
}
a[left] = p;
return left;
}
}
最新文章
- jQuery对表格的操作及其他应用
- JS前台base32加密,C#后台解码
- CSS3简单动画
- Linux下MySQL忘记密码
- 让你的APP支持iPhone5
- [游戏模版6] Win32 graph
- 【AdaBoost算法】强分类器训练过程
- Spring Boot 3 Hibernate
- (转)C#调用非托管Win 32 DLL
- [置顶] myEclipse8.5或者eclipse手工安装jd插件(myEclipse8.5或eclipse内直接查看.class文件,jd反编译工具)
- 标题:a++和++a的区别
- 单源最短路径问题-Dijkstra算法
- Java I/O---获取文件目录并写入到文本
- 《并行程序设计导论》——Pthreads
- 三大家族(offset、scroll、client)
- XVII Open Cup named after E.V. Pankratiev. GP of Tatarstan
- 图解 (a + b) * (a + b) == a**2 + 2*a*b + b**2
- HNOI2019 游记
- SSD垃圾回收
- 22状态模式State
热门文章
- Spring IoC底层原理
- AFNetworking 不支持 text/plain,unacceptable content-type: text/plain
- curl传post数据流
- qt学习(二) buttong layout spinbox slider 示例
- BFS入门
- CoderForces 518C Anya and Smartphone (模拟)
- metasploit-数据库支持
- csdn的blog可以直接导入内含图片的word文档吗?
- shell 脚本 查看班上同学的网络状态
- Give $20/month and provide 480 hours of free education