【day-17】快排寻找第K小的数,简化版本

#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
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值