二分查找算法 Binary Search Algorithm

common algorithms 二分查找算法

  1. Binary search二分查找算法 is a classic algorithm used to efficiently locate a target value within a sorted array
// Binary search is a classic algorithm used to efficiently locate a target value within a sorted array
//Measure-Command { .\main.exe } to get the running time


#include "stdio.h"
#include <time.h>
typedef unsigned char uint8_t;

uint8_t binary_search(uint8_t* array, uint8_t target, uint8_t left, uint8_t right)
{
   uint8_t mid ;

   while(left < right)
   {
       mid = (left + right)/2; // get the mid index

       if (array[mid] > target)
       {
          right--;
       }
       else if (array[mid] < target)
       {
          left++;
       }
       else 
       {
          return (mid);
       }
   }

   return (0xff); // no target
}

void main(void)
{
       // Record the start time
   clock_t start_time = clock();

   uint8_t array[8] = {1, 2, 3, 4, 5, 6, 7, 8} ;     // sorted increase

   uint8_t target = 7;

   uint8_t len =  sizeof(array)/sizeof(array[0]);

   uint8_t ret;

   ret = binary_search(array, target, 0, (len - 1));

   printf("\n\n");
   printf("Hello, Lihua Long, good job!!\n");
   printf("the index search is :%d\n", ret);

}

// running result by the cmd (./main) :

// Hello, Lihua Long, good job!!
// the index search is :6

// running result by the cmd (./main to run main.exe) :
// Days              : 0
// Hours             : 0
// Minutes           : 0
// Seconds           : 0
// Milliseconds      : 40
// Ticks             : 401391
// TotalHours        : 1.114975E-05
// TotalMinutes      : 0.000668985
// TotalSeconds      : 0.0401391
// TotalMilliseconds : 40.1391

在这里插入图片描述

二分查找算法Binary Search Algorithm)是一种在已排序数组中查找特定元素的算法算法通过将目标值与数组的中间元素进行比较,并根据比较结果将搜索范围缩小一半。若目标值等于中间元素,则找到目标值;若目标值小于中间元素,则在左半部分继续查找;若目标值大于中间元素,则在右半部分继续查找。重复以上步骤直到找到目标值或搜索范围为空。 下面是用中文编写的二分查找算法search_bin的示例代码: ```python def search_bin(arr, target): left = 0 right = len(arr) - 1 while left <= right: mid = (left + right) // 2 if arr[mid] == target: return mid if arr[mid] < target: left = mid + 1 else: right = mid - 1 return -1 ``` 在以上示例代码中,search_bin函数接收一个已排序的数组arr和目标值target作为参数,返回目标值在数组中的索引。算法开始时,定义左边界left为数组的第一个元素的索引,右边界right为数组的最后一个元素的索引。使用while循环,在左边界小于等于右边界的条件下进行查找。 在每次循环中,计算中间元素的索引mid,并与目标值进行比较。如果中间元素等于目标值,表示找到目标值,返回中间元素的索引。如果中间元素小于目标值,说明目标值在右半部分,将左边界更新为mid+1,继续查找右半部分。如果中间元素大于目标值,说明目标值在左半部分,将右边界更新为mid-1,继续查找左半部分。 当左边界大于右边界时,表示搜索范围为空,说明未找到目标值,返回-1表示搜索失败。 经过以上步骤,当目标值存在于已排序数组中时,二分查找算法能够高效地找到目标值的索引。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值