• 二分查找、中位数查找


    注意递归停止的要求,要么中间找到返回m

              要么start==end找到返回m,

              要么还是找不到,返回-1.

    int Binary_search(int *a,int start,int end,int x){
      if(start==end){
        if(a[start]==x)
          return start;
        else
          return -1;
      }
      int m=(start+end)/2;
      if(x>a[m]){
        Binary_search(a,m+1,end,x);
      }
      else if(x<a[m]){
        Binary_search(a,start,m-1,x);
      }
      else
        return m;
    }

    void swap(int a, int b){
    int temp=a;
    a=b;
    b=temp;
    }

    中位数查找:在大小为N的数组中查找第k大(1<=k<=n)的数字并返回。

    int Median_search(int *a,int start,int end,int x){
      if(end-start+1<x)
      return -1;
      int j=start;
      for(int i=start+1;i<end;i++){
        if(a[i]<a[start]){
          ++j;
          swap(a[i],a[j]);
        }
      }
      swap(a[start],a[j]);
      if(j-start+1==x){
        return a[j];
      }
      else if(j-start+1>x)
        return Median_search(a,start,j-1,x);
      else
        return Median_search(a,j+1,end,x+start-j-1);
    }

  • 相关阅读:
    【20171227】json
    【20171224】文件操作
    【20171225】编解码
    【20171226】urllib
    【20171226】requests
    【错误集】编解码
    Python 基础概念——单例设计模式
    Python 继承
    python面向对象概述
    Python基础_函数的递归
  • 原文地址:https://www.cnblogs.com/huangshan/p/3386704.html
Copyright © 2020-2023  润新知