【day-17】快排寻找第K小的数,简化版本
来源:互联网 发布:佛经诵读软件 编辑:程序博客网 时间:2024/05/29 07:44
#include <iostream>#include <vector>using namespace std;int quickSortFindK(vector<int>& array,int start,int end,int k){ if(start>end){ return -1; } int first=start; int last=end; int key=array[first]; while(last>first){ while(last>first &&array[last]>=key){ last--; } array[first]=array[last]; while(last>first&&array[first]<=key){ first++; } array[last]=array[first]; } array[first]=key; //第k小的数的下标为k-1 if(first==k-1){ return array[first]; }else if(first>k-1){ return quickSortFindK(array,start,first-1,k); }else{ return quickSortFindK(array,first+1,end,k); }}int quickSort(vector<int>& array,int start,int end){ if(start>end){ return -1; } int first=start; int last=end; int key=array[first]; while(last>first){ while(last>first &&array[last]>=key){ last--; } array[first]=array[last]; while(last>first&&array[first]<=key){ first++; } array[last]=array[first]; } array[first]=key; quickSort(array,start,first-1); quickSort(array,first+1,end);}using namespace std;int main(){ vector<int> array{3,2,34,22,3,4,55,6,22,3,555,6}; auto array1=array; //寻找第三小的数 int Ksmall=3; cout<<quickSortFindK(array,0,array.size()-1,Ksmall)<<endl; quickSort(array1,0,array.size()-1); for(auto it=array1.begin();it!=array1.end();it++){ cout<<*it<<" "; } cout<<endl; return 0;}
阅读全文
0 0
- 【day-17】快排寻找第K小的数,简化版本
- 快排算法及利用快排思想寻找第k大(小)的数
- 寻找第K大的数(快排思想)
- 【day-10】寻找前K大个数-快排
- 快排的思想求第K小的数
- 快排思想找第k小的数
- 寻找无序数组中第k大的数——快排思想
- 20170927_快排应用_数组中寻找第K小的数字
- java快排,找第K小的数,找前K个数
- 寻找第k大数(快排思想)
- 基于快排的选择算法:返回数组中第k小的数
- 快排划分思想的应用-求第k大数或者第k小的数(求前k大数或者前k小的数)
- 寻找第K小的数
- 寻找第K小的数
- 寻找第K小的数
- 寻找第K小的数
- 分治-寻找第k小的数
- 分治法 快排 输出第k大的数
- Java ArrayList subList(..)的坑
- 如何用Spring完成数据库的事物?
- PHP--Curl模拟POST请求
- 报错 java.lang.IllegalArgumentException: Not a managed type: class com.yzf.cloud.model.User
- IntelliJ 快捷输出方式
- 【day-17】快排寻找第K小的数,简化版本
- php7 curl文件上传问题
- UVA 10382 Watering Grass (贪心)
- 字符串的排列
- 制作升级包脚本
- 如何为 angularjs 路由中的每个视图指定 css
- Altium designer不显示飞线的三种方法
- 手写数学公式识别器
- CSS布局之-高度自适应