算法导论9.2-3习题解答(寻找第i小的数)
生活随笔
收集整理的這篇文章主要介紹了
算法导论9.2-3习题解答(寻找第i小的数)
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
CLRS 9.2-3 :
寫出RANDOMIZED-SELECT的一個迭代版本
在這里,順便實現在數組內尋找第i小的數值。
#include <iostream> #include <time.h> using namespace std; //隨機化分割 int randomized_partition(int* a, int p, int r); int randomized_select(int* a, int p, int r, int i); int main() {int arr[10] = {4, 34, 21, 8, 3, 10, 453, 32, 1, 400};int n;while(true){cout<<"輸入第n小的數:"<<endl;cin>>n;cout<<randomized_select(arr, 0, 9, n - 1)<<endl;}return 0; } //下標為[p, r]之間的元素 int randomized_partition(int* a, int p, int r) {srand(time(NULL));int q = rand()%(r - p + 1) + p;int temp = a[q];a[q] = a[r];a[r] = temp;int j = p;for(int i = p; i < r; i++){if(a[i] < a[r]){if(i != j){int temp2 = a[i];a[i] = a[j];a[j] = temp2;}j++;}}temp = a[j];a[j] = a[r];a[r] = temp;return j; } //迭代版本 int randomized_select(int* a, int p, int r, int i) {int q = randomized_partition(a, p, r);while(p != r){if(i == q)return a[q];else if(i < q){r = q - 1;q = randomized_partition(a, p, r);}else{p = q + 1;q = randomized_partition(a, p, r);}}return a[p]; }?
轉載于:https://www.cnblogs.com/null00/archive/2011/04/12/2065065.html
總結
以上是生活随笔為你收集整理的算法导论9.2-3习题解答(寻找第i小的数)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: WPF纯手工两步打造图片切割工具(一)
- 下一篇: Red Hat Enterprise L