二分查找算法 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

在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值