Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
38 changes: 38 additions & 0 deletions Binary search
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
ecursive Method)
Python
Java
C
C++
// Binary Search in C

#include <stdio.h>

int binarySearch(int array[], int x, int low, int high) {
if (high >= low) {
int mid = low + (high - low) / 2;

// If found at mid, then return it
if (array[mid] == x)
return mid;

// Search the left half
if (array[mid] > x)
return binarySearch(array, x, low, mid - 1);

// Search the right half
return binarySearch(array, x, mid + 1, high);
}

return -1;
}

int main(void) {
int array[] = {3, 4, 5, 6, 7, 8, 9};
int n = sizeof(array) / sizeof(array[0]);
int x = 4;
int result = binarySearch(array, x, 0, n - 1);
if (result == -1)
printf("Not found");
else
printf("Element is found at index %d", result);
}