Add 01_binary_search.c (#68)
* Add 01_binary_search.c * Update use sizeof and floor
This commit is contained in:
committed by
Aditya Bhargava
parent
f24b9a6e35
commit
9744af50ed
39
01_introduction_to_algorithms/c/01_binary_search.c
Normal file
39
01_introduction_to_algorithms/c/01_binary_search.c
Normal file
@@ -0,0 +1,39 @@
|
|||||||
|
#include <stdio.h>
|
||||||
|
#include <math.h>
|
||||||
|
|
||||||
|
int binarySearch(int[], int, int);
|
||||||
|
|
||||||
|
int main()
|
||||||
|
{
|
||||||
|
int myList[] = {1, 3, 5, 7, 9};
|
||||||
|
int len = sizeof(myList) / sizeof(myList[0]);
|
||||||
|
|
||||||
|
printf("%d\n", binarySearch(myList, 3, len)); // 1
|
||||||
|
printf("%d\n", binarySearch(myList, -1, len)); //-1
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
int binarySearch(int list[], int item, int len)
|
||||||
|
{
|
||||||
|
int low = 0;
|
||||||
|
int high = len;
|
||||||
|
while (low <= high)
|
||||||
|
{
|
||||||
|
int mid = floor((low + high) / 2); //math.h floor
|
||||||
|
int guess = list[mid];
|
||||||
|
|
||||||
|
if (guess == item)
|
||||||
|
{
|
||||||
|
return mid;
|
||||||
|
}
|
||||||
|
else if (guess > item)
|
||||||
|
{
|
||||||
|
high = mid - 1;
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
low = mid + 1;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return -1; //number not find
|
||||||
|
}
|
||||||
Reference in New Issue
Block a user