问题描述
- randomized select 算法工作错误
-
算法导论算法,来实现查找第 i 小的数,不能正常工作#include<stdio.h> #include<stdlib.h> #include<time.h> int randomized_select(int *arr, int start, int end, const int i); //int pivot; int main() { int a[10] = {1, 9, 4, 3, 8, 2, 5, 6, 10, 7}; //printf("%d", randomized_select(a, 0, 9, 2) ); int num = randomized_select(a, 0, 9, 2); return 0; } /* * 返回数组 arr 下标 start 至 end 中第 i小的元素 */ int randomized_select(int *arr, int start, int end, int i) { if(start == end) { return arr[start]; } srand( ( unsigned )time(NULL) ); int pivot = start + rand() % (end - start); //int pivot = rand() % (end - start + 1 ) + start; // 主元 int k = pivot - start + 1; if(i == k) // the pivot value is the answer. { return arr[pivot]; } else if(i < k) { return randomized_select(arr, start, pivot - 1, i); } else//(i >= k) { return randomized_select(arr, pivot + 1 , end, i - k); } }
解决方案
http://www.cnblogs.com/sun/archive/2008/07/10/1239999.html
解决方案二:
http://blog.csdn.net/mishifangxiangdefeng/article/details/7687733
http://www.cnblogs.com/hibernate6/archive/2011/05/19/2522294.html
http://www.cnblogs.com/weixliu/archive/2012/12/23/2830199.html
希望对你有用!!!
时间: 2024-09-07 06:16:55