求一组数据中最大/第二大等等的O(N)算法

    在《算法导论》中看到的,自己实现了一下。

#include <cstdio>
#include <windows.h>
#include <time.h>
void swap(int *a,int *b)
{
    int c=*a;
    *a=*b;
    *b=c;
}
int* Random_Selector(int *Left,int *Right)
{
    int Average=*(Left+rand()%(Right-Left+1)-1);
    while(Left<Right){
        while(Left<Right&&(*Left)<=Average)Left++;
        while(Left<Right&&(*Right)>=Average)Right--;
        if(Left<Right)swap(Left,Right);
    }
    return Left<Right?Left:Right;
}
int* SearchIndex(int *Left,int *Right,int index)
{
    int* r=Random_Selector(Left,Right);
    if(r-Left==index-1)return r;
    if(r-Left<index-1)return SearchIndex(r,Right,index-(r-Left));
    return SearchIndex(Left,r-1,index);
}
void initialize()
{
    srand(time(0));
}
int main()
{
    initialize();
    int index=0;
    int test[]={1,2,3,4,5,6,7,8,9};
    int *r;
    while(++index!=10){
        r=SearchIndex(test,test+8,index);
        printf("Index %d is %d\n",index,*r);
    }
    return 0;
}



 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值