zoukankan      html  css  js  c++  java
  • 二分查找----第一种(相同元素返回不确定哪个)

     1 /*
     2  *binary search 
     3  *just return a value position equals the find but may not the first one
     4  *we should caution the left open right close or left close and right close rules to not happen the boundary error
     5  */
     6 
     7 #include <stdio.h>
     8 #include <stdlib.h>
     9 #include <string.h>
    10 
    11 /*
    12  *binary search
    13  *return -1 can not find the number else the position of the number
    14  */
    15 
    16 int binary_search(int in_arr[],int n,int value)
    17 {
    18     int left,right,middle;
    19     left = 0,right = n - 1;
    20 
    21     while(left <= right)
    22     {
    23         middle = left + (right - left) / 2; //can solve the number overflow error
    24         
    25         if(value > in_arr[middle])
    26         {
    27             left = middle + 1;
    28         }
    29         else if(value < in_arr[middle])
    30         {
    31             right = middle - 1;
    32         }
    33         else
    34         {
    35             return middle;
    36         }
    37     }
    38 
    39     return -1;
    40 }
    41 
    42 int main()
    43 {
    44     int i,value,in_arr[10];
    45 
    46     for(i = 0; i < 10; i++)
    47     {
    48         scanf("%d",&in_arr[i]);
    49     }
    50     
    51     while(1)
    52     {
    53         printf("input the value to find
    ");
    54 
    55         scanf("%d",&value);
    56 
    57         int index = binary_search(in_arr,10,value);
    58 
    59         if(index == -1)
    60         {
    61             printf("can not find the number %d 
    ",value);
    62         }
    63         else
    64         {
    65             printf("the value %d is at the position %d
    ",value,index);
    66         }
    67     }
    68 }
  • 相关阅读:
    day2-元组 列表-赋值和深浅拷贝
    day1-bytes类型 三元运算 进制
    DAY02
    DAY02
    Python格式化、显示颜色
    DAY02
    DAY02
    DAY02
    DAY02
    DAY02
  • 原文地址:https://www.cnblogs.com/daimadebanyungong/p/4914561.html
Copyright © 2011-2022 走看看