zoukankan      html  css  js  c++  java
  • 二分查找----(返回第一个找到的值)

    二分查找需要注意两个问题一个是临界问题,流行的方案是左开右闭区间方式,还有一个就是当数组元素中有多个相同待查找值的应该返回第一个,下面的代码可以解决这问题,记录一下,由于最近开始用gvim编程了,请原谅我的中式英语注释。

     1 /*
     2  * binary search from programing perls
     3  * this binary search can solve the problem of when there are same value can not return the fisrt match number
     4  */
     5 #include <stdio.h>
     6 #include <stdlib.h>
     7 #include <string.h>
     8 
     9 
    10 /*
    11  * binary search 
    12  * return -1 can not find the number    else the position of the number
    13  */
    14 
    15 int binary_search(int in_arr[],int n,int value)
    16 {
    17     int left,right,middle;
    18     
    19     left = -1,right = n;
    20     
    21     while(left + 1 != right)
    22     {
    23         middle = left + (right - left) / 2; //to prevent the overflow of the int if use middle = (right + left) / 2
    24 
    25         if(value > in_arr[middle])
    26         {
    27             left = middle;
    28         }
    29         else
    30         {// delete one compare(but can add compare times) 
    31             right = middle;
    32         }
    33     }
    34 
    35     if(right >= n || in_arr[right] != value)
    36     {
    37         right = -1;
    38     }
    39 
    40     return right;
    41 }
    42 
    43 
    44 int main()
    45 {
    46     int i,value,in_arr[10];
    47     
    48     memset(in_arr,0,sizeof(in_arr));
    49     
    50     for(i = 0; i < 10; i++)
    51     {
    52         scanf("%d",&in_arr[i]);
    53     }
    54     
    55     while(1)
    56     {
    57         printf("input the value you want to find :
    ");
    58         
    59         scanf("%d",&value);
    60 
    61         int index = binary_search(in_arr,10,value);
    62 
    63         if(index == -1)
    64         {
    65             printf("can not find the value
    ");
    66         }
    67         else
    68         {
    69             printf("the %d at the position %d
    ",value,index);
    70         }
    71     }
    72     
    73     return 0;    
    74 }
  • 相关阅读:
    c# 与 winform 界面开发
    文件大小的友好输出及其 Python 实现
    bookhub -- 扁平化本地电子书管理与分享工具
    阶段性放弃 wxPython 前的总结
    数据挖掘环境下的个人信息安全
    精益阅读 -- 科技图书的阅读过程管理工具
    wxPython Modal Dialog 模式对话框
    wxPython 基本框架与运行原理 -- App 与 Frame
    JAVA向,二叉查找树
    线性表实践-选票算法
  • 原文地址:https://www.cnblogs.com/daimadebanyungong/p/4914584.html
Copyright © 2011-2022 走看看