How to write a c program to binary search in C Programming ?
Solution:
#include <stdio.h>
#define SIZE 7
void bubbleSort(int *A, int length);
int binarySearch(int *A, int start, int end, int value);
int main()
{
int arr[SIZE] = {11, 1, 8, 5, 6, 8, 4};
int i;
bubbleSort(arr, SIZE);
for(i = 0; i < SIZE; i++)
printf("%d ", arr[i]);
printf("\n");
printf("%d\n", binarySearch(arr, 0, SIZE - 1, 3));
return 0;
}
void bubbleSort(int *A, int length)
{
int i, j;
for(i = 1; i <= length - 1; i++)
{
for(j = 0; j < length - i; j++)
if(A[j] > A[j + 1])
{
int temp = A[j];
A[j] = A[j + 1];
A[j + 1] = temp;
}
}
}
int binarySearch(int *A, int start, int end, int value)
{
int mid = (start + end) / 2;
if(start > end) return -1;
else if(A[mid] == value) return mid;
else if(value < A[mid]) return binarySearch(A, start, mid - 1, value);
else return binarySearch(A, mid+ 1, end, value);
}
https://en.wikipedia.org/wiki/Binary_search_algorithm