Quikselect -code

本文介绍了一种线性时间复杂度的快速选择算法,该算法能在未排序数组中找到第k小的元素。通过递归地将数组部分排序,快速选择算法能够实现O(n)的时间复杂度,优于传统的排序方法。文章提供了详细的C++实现示例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

What is Quick Select Algorithm? How to implement in C++?

  • The QuickSelect algorithm quickly finds the k-th smallest element of an unsorted array of n elements.
  • It is an O(n), worst-case linear time, selection algorithm. A typical selection by sorting method would need atleast O(n log n) time.
  • This algorithm is identical to quick sort but it does only a partial sort, since we already know which partition our desired element lies as the pivot is in final sorted position.
#include <iostream> using namespace std; // A simple print function void print(int *input) { for ( int i = 0; i < 5; i++ ) cout << input[i] << " "; cout << endl; } int partition(int* input, int p, int r) { int pivot = input[r]; while ( p < r ) { while ( input[p] < pivot ) p++; while ( input[r] > pivot ) r--; if ( input[p] == input[r] ) p++; else if ( p < r ) { int tmp = input[p]; input[p] = input[r]; input[r] = tmp; } } return r; } int quick_select(int* input, int p, int r, int k) { if ( p == r ) return input[p]; int j = partition(input, p, r); int length = j - p + 1; if ( length == k ) return input[j]; else if ( k < length ) return quick_select(input, p, j - 1, k); else return quick_select(input, j + 1, r, k - length); } int main() { int A1[] = { 100, 400, 300, 500, 200 }; cout << "1st order element " << quick_select(A1, 0, 4, 1) << endl; int A2[] = { 100, 400, 300, 500, 200 }; cout << "2nd order element " << quick_select(A2, 0, 4, 2) << endl; int A3[] = { 100, 400, 300, 500, 200 }; cout << "3rd order element " << quick_select(A3, 0, 4, 3) << endl; int A4[] = { 100, 400, 300, 500, 200 }; cout << "4th order element " << quick_select(A4, 0, 4, 4) << endl; int A5[] = { 100, 400, 300, 500, 200 }; cout << "5th order element " << quick_select(A5, 0, 4, 5) << endl; }
OUTPUT:-
1st order element 100
2nd order element 200
3rd order element 300
4th order element 400
5th order element 500
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值