TheAlgorithms-C/searching/other_binary_search.c

47 lines
867 B
C
Raw Normal View History

2017-05-12 03:43:02 +03:00
#include <stdio.h>
#include <stdlib.h>
#define len 5
2017-11-20 10:08:47 +03:00
int binarySearch(int array[], int leng, int searchX)
2017-05-12 03:43:02 +03:00
{
int pos = -1, right, left, i = 0;
2017-11-20 10:08:47 +03:00
left = 0;
right = leng - 1;
2017-11-20 10:08:47 +03:00
while (left <= right)
{
pos = left + (right - left) / 2;
if (array[pos] == searchX)
{
return pos;
}
else if (array[pos] > searchX)
{
right = pos - 1;
}
else
{
left = pos + 1;
}
}
return -1; /* not found */
2017-05-12 03:43:02 +03:00
}
2020-04-08 16:41:12 +03:00
int main(int argc, char *argv[])
2017-05-12 03:43:02 +03:00
{
int array[len] = {5, 8, 10, 14, 16};
2017-11-20 10:08:47 +03:00
int position;
position = binarySearch(array, len, 5);
2017-11-20 10:08:47 +03:00
if (position < 0)
printf("The number %d doesnt exist in array\n", 5);
else
{
printf("The number %d exist in array at position : %d \n", 5, position);
}
2017-11-20 10:08:47 +03:00
return 0;
2017-05-12 03:43:02 +03:00
}