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