从一个数组中找出第k小元素的随机化算法 c语言实现 算法导论第九章
2013-08-05 21:45
351 查看
//Randomized_select,select a particular number from an array in linear time #include <stdio.h> #include <stdlib.h> void swap(int *p,int *q)//交换元素 { int temp; temp=*p; *p=*q; *q=temp; } int Random(int p,int r)//产生p与r之间的一个随机数 { int result=p+rand()%(r-p+1); return result; } int partition(int A[],int p,int q)//划分 { int j=p,i=j-1; int r=A[q]; for(int k=p;k<q;k++) { if(A[k]<=r) { i=i+1; swap(&A[i],&A[k]); } } swap(&A[i+1],&A[q]); return i+1; } int Randomized_partition(int A[],int p,int r)//随机划分过程 { int i=Random(p,r); swap(&A[i],&A[r]); return partition(A,p,r); } int Random_select(int A[],int p,int r,int i)//select the ith element { if(p==r) return A[p];//If there is only one array,then just return the only element int q,k; q=Randomized_partition(A,p,r);//the partition of the array k=q-p+1;//the location of A[q] if(i==k)//k is the right place return A[q]; else if(i<k) return Random_select(A,p,q-1,i); else return Random_select(A,q+1,r,i-k); } void main() { int A[]={0,4,3,5,6,1,8,9}; int x=Random_select(A,1,7,6); printf("the 2th number is %d\n",x); }
相关文章推荐
- 从一个数组中同时找出最大最小数-算法导论第九章
- 算法导论:快速找出无序数组中第k小的数
- 算法(三)找出数组中第K大元素
- java 实现从无序数组中 找出第k大的数, 无序数组充许有重复元素
- C语言 选择排序算法原理和实现 从数组中 找出最小的元素然后交换位置
- 一个含n个元素的整数数组至少存在一个重复数, 请编程实现,在O(n)时间内找出其中任意一个重复数。
- 算法之找出数组中出现次数大于n/m的元素
- JavaScript实现删除数组重复元素的5种常用高效算法总结
- 程序员面试100题(算法)之找出数组中两个只出现一次的数字(位运算实现)
- 用线性时间复杂度实现找出数组中出现一次的元素
- 【算法导论】10.1-5单数组实现双端队列
- 一个简单的算法---实现找出数组中一个数字出现次数最多的数字
- 算法导论4.1-3~4.1-5最大子数组暴力算法和递归算法的实现和线性时间算法实现
- Java实现 找出数组中出现次数超过数组长度一半的元素
- 数组实现堆排序(来源算法导论)
- 用线性时间复杂度实现找出数组中出现一次的元素
- 算法题:找出一个数组中依次最大的k个元素
- 用JAVA编写一个算法实现对一个字符数组的所有元素的所有组合
- C语言找出数组中的特定元素的算法解析