算法--选择第K小的数
2014-01-10 10:26
363 查看
算法基本思想是对输入的数组进行递归划分,这样得到一个中轴元素pivot,左边数组内的数都小于等于中轴元素pivot,右边的数组都大于等于pivot,然后考察左边数组加上中轴元素的个数x,若个数x==k,则返回pivot;若x>k,则说明第K小元素在左边数组并且是第k小元素,继续递归查找;若x<k,则说明第K小元素在右边数组并且是第k-x小元素。综合上面的思想得到代码如下:
由于C语言的随机数函数比较难用,这里用的是Java语言实现.
private int rand(int x,int y){ if(x>y) return rand(y,x); return (int)(Math.random()*(y-x)+x); } private int randomizedPartition(int A[],int low,int high){ int p=rand(low,high); //exchange A[low]<->A[p] int key=A[low]; A[low]=A[p]; A[p]=key; //set the key value key=A[low]; while(low<high){ while(low<high&&A[high]>=key)high--; A[low]=A[high]; while(low<high&&A[low]<=key)low++; A[high]=A[low]; } A[low]=key; return low; } public int randomizedSelect(int A[],int s,int t,int i){ if(s==t) return A[s]; int p=randomizedPartition(A,s,t); int k=p-s+1; if(k==i) return A[p]; else if(k>i) return randomizedSelect(A,s,p-1,i); else return randomizedSelect(A,p+1,t,i-k); }
由于C语言的随机数函数比较难用,这里用的是Java语言实现.
相关文章推荐
- 程序员面试题精选100题(28)-字符串的排列[算法]
- Go语言最佳实践——面向对象
- Invoke and BeginInvoke
- android自动添加程序桌面快捷方式
- easyui更改messager的OkCancel按钮为(中文)确定取消
- 浅谈Linux PCI设备驱动
- A Difficult Customer
- nagios故障,求解?
- 请看到我的博客的朋友留下你的脚印
- 重写QcomboBox
- 可延迟函数、内核微线程以及工作队列
- SQL SERVER 使用select和union插入多条数据
- JQuery学习笔记--01
- 贴片电阻各种封装规格及阻值标注方法
- PopupWindow的使用
- C++ MFC字体设置
- 从Proxy-Stub到aidl
- setTimeout自动触发一个js。
- 关于MSDTC - 与基础事务管理器的通信失败 错误解决的小备忘
- android自定义文本框,后面带清空按钮