【C++】线性时间选择

2023-12-31 22:22:20
#include <iostream>
#include <vector>
using namespace std;

void swap(vector<int>& nums, int a, int b)
{
    int temp = nums[a];
    nums[a] = nums[b];
    nums[b] = temp;
}

int linear_select(vector<int>& nums, int begin, int end, int target)
{
    int i = begin;
    int j = end;
    int pivot = begin;

    while(i<j){
        while(i<j && nums[j]>=nums[pivot]){
            j--;
        }
        while(i<j && nums[i]<=nums[pivot]){
            i++;
        }
        swap(nums, i, j);
    }

    swap(nums, pivot, i);

    int order = i-begin+1;
    if(order==target){
        return nums[j];
    }
    else if(order < target){
        return linear_select(nums, j+1, end, target-order);
    }
    else{
        return linear_select(nums, begin, j-1, target);
    }
}


int main() {
    vector<int> array1 = {1,5,4,3,2,9,8,6,7,0};
    vector<int> array2 = {1,2,3,4,5,6,7,8,9,10};

    int ans1 = linear_select(array1, 0, array1.size()-1, 5);
    int ans2 = linear_select(array2, 0, array2.size()-1, 5);

    cout << ans1 << endl << ans2 << endl;

    return 0;
}

文章来源:https://blog.csdn.net/weixin_63160898/article/details/135309929
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。