欢迎来到入门教程网!

C语言

当前位置:主页 > 软件编程 > C语言 >

C经典算法之二分查找法

来源:本站原创|时间:2020-01-10|栏目:C语言|点击:

C经典算法之二分查找法

1.根据key查找所在数组的位置

#include <stdio.h>
/*
 key = 9;
 1 2 3 4 5 6 7 8
 arr 3, 4, 5, 7, 9 , 11, 21, 23
 low = 1  mid = (low + high)/2 = 4      high = 8;
 one   arr[mid] = 7 < 9;  so low = mid + 1 = 5; high = 8; mid = (low + high)/2 = 6
 two   arr[mid] = 11 > 9  so low = 5 ,   high = mid - 1 = 5 mid = 5;
 arr[mid] = 9 == key

 if(key = 10) low = mid + 1 > high

 */
int main(int argc, const char * argv[])
{
 int findByHalf(int arr[], int len, int key);

 int arr[] = {3, 4 , 5, 7, 9 , 11, 21, 23};
 int len = sizeof(arr)/sizeof(int);

 int index = findByHalf(arr, len, 88);

 printf("index = %d\n", index);
 return 0;
}

int findByHalf(int arr[], int len, int key){
 int low = 0;
 int high = len - 1;

 int mid ;


 while(low <= high){
  mid = (low + high) / 2;
  //右边查找
  if (key > arr[mid]) {
   low = mid + 1;
  //左边查找
  }else if (key > arr[mid]) {
   high = mid - 1;
  }else{
   return mid;
  }

 }
 return -1;
}

2.插入一个数,得到其所在数组的位置

#include <stdio.h>
/*
 key = 9;
 1 2 3 4 5 6 7 8
 arr 3, 4, 5, 7, 9 , 11, 21, 23
 low = 1  mid = (low + high)/2 = 4      high = 8;
 one   arr[mid] = 7 < 9;  so low = mid + 1 = 5; high = 8; mid = (low + high)/2 = 6
 two   arr[mid] = 11 > 9  so low = 5 ,   high = mid - 1 = 5 mid = 5;
 arr[mid] = 9 == key

 if(key = 10) low = mid + 1 > high

 */
int main(int argc, const char * argv[])
{
 int findByHalf(int arr[], int len, int key);

 int arr[] = {3, 4 , 5, 7, 9 , 11, 21, 23};
 int len = sizeof(arr)/sizeof(int);

 int index = findByHalf(arr, len, 88);

 printf("index = %d\n", index);
 return 0;
}

int insertByHalf(int arr[], int len, int key){
 int low = 0;
 int high = len - 1;

 int mid ;


 while(low <= high){
  mid = (low + high) / 2;
  //右边查找
  if (key > arr[mid]) {
   low = mid + 1;
  //左边查找
  }else if (key > arr[mid]) {
   high = mid - 1;
  }else{
   //如果arr[mid] == key
   //就把key插入到这个数的后面
   return mid + 1;
  }

 }
 //如果low > high 说明 key > arr[mid];
 //就把key插入到low对应的 这个数的位置
 return low;
}

如有疑问请留言或者到本站社区交流讨论,感谢阅读,希望能帮助到大家,谢谢大家对本站的支持!

上一篇:C++使用redis的实例详解

栏    目:C语言

下一篇:亚马逊经典面试题实例详解

本文标题:C经典算法之二分查找法

本文地址:https://www.xiuzhanwang.com/a1/Cyuyan/1119.html

网页制作CMS教程网络编程软件编程脚本语言数据库服务器

如果侵犯了您的权利,请与我们联系,我们将在24小时内进行处理、任何非本站因素导致的法律后果,本站均不负任何责任。

联系QQ:835971066 | 邮箱:835971066#qq.com(#换成@)

Copyright © 2002-2020 脚本教程网 版权所有