Skip to content

Instantly share code, notes, and snippets.

@ArtyomLazyan
Created March 12, 2017 09:43
Show Gist options
  • Save ArtyomLazyan/2cfb7ac17b5c16ea0ac8768e5c27b12c to your computer and use it in GitHub Desktop.
Save ArtyomLazyan/2cfb7ac17b5c16ea0ac8768e5c27b12c to your computer and use it in GitHub Desktop.
BINARY SEARCH
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
/**************************** BINARY SEARCH *******************************/
int A[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12 };
int binarySearch(int Arr[], int size, int num)
{
int start = 0, end = size - 1;
int mid = 0;
while (start <= end)
{
mid = (start + end) / 2;
if (Arr[mid] == num)
return mid;
else if (Arr[mid] < num)
start = mid + 1;
else
end = mid - 1;
}
return -1;
}
int main()
{
int index = binarySearch(A, 12, 11);
if (index == -1)
printf("Error\n");
else
printf("Index = %d\n", index + 1);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment