快速排序算法的拓展和应用(寻找前k个最小值,寻找数组中数量超过一半的值)

# include <iostream>
# include <vector>

using namespace std;

//快速排序算法
int Partition(vector<int>* a, int begin, int end){
    int i = begin;
    int j = end;
    int key = (*a)[begin];
    while(i<j){
        while(i<j && key <= (*a)[j]){
            j--;
        }
        (*a)[i] = (*a)[j];
        while(i<j && key >= (*a)[i]){
            i++;
        }
        (*a)[j] = (*a)[i];
    }
    (*a)[i] = key;
    return i;
}

void find_the_small_values(vector<int>* a,int k, vector<int>* result){
    if(a==NULL){
        return;
    }
    else{
        int first = 0;
        int last = int(a->size()-1);
        //利用快排,index前面的元素小,index后面的元素大
        int index = Partition(a,first,last);
        while(index!=k){
            //index前面的元素个数小于k个
            if(index<k){
                //继续往后找
                first = index + 1;
                index = Partition(a,first,last);
            }
            //index前面的元素个数大于k个
            else{
                //继续往前查找
                last = index - 1;
                index = Partition(a,first,last);
            }
        }
        //取k位置前面的k个小元素作为输出
        if(index == k){
            for(int i = 0;i<k;i++){
                result->push_back((*a)[i]);
            }
        }
    }
}

int find_the_half_values(vector<int>* a){
    if(a==NULL){
        return 0;
    }
    else{
        int first = 0;
        int last = int(a->size()-1);
        int index = Partition(a,first,last);
        int mid = last >> 1;
        //和上面函数原理一样,不过这里为了找到数组的中位数
        while(index!=mid){
            if(index<mid){
                first = index + 1;
                index = Partition(a,first,last);
            }
            else{
                last = index - 1;
                index = Partition(a,first,last);
            }
        }
        int count = 0;
        //判断中位数的个数是否满足要求
        if(index == mid){
            for(auto i = a->begin();i!=a->end();i++){
                if((*a)[index] == *i){
                    count++;
                }
            }
        }
        if(2*count>int(a->size())){
            return (*a)[mid];
        }
        else{
            return 0;
        }
    }
}

int main(){
    vector<int>* a = new vector<int>;
    vector<int>* result = new vector<int>;
    *a = {1,2,1,2,1,1,5};
    find_the_small_values(a,3,result);
    for(auto i = result->begin();i!=result->end();i++){
        cout << *i << "->";
    }
    cout << endl;
    int count = find_the_half_values(a);
    cout << "the half value" << count;
    return 0;
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值