0% found this document useful (0 votes)
19 views4 pages

Assingment 2 (B)

The document contains two implementations of binary search in C: a recursive version and a non-recursive version. Both methods search for a specified element in a sorted array and return its index if found, or -1 if not found. Example arrays and test cases are provided for each implementation.

Uploaded by

aj99883355
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as ODT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
19 views4 pages

Assingment 2 (B)

The document contains two implementations of binary search in C: a recursive version and a non-recursive version. Both methods search for a specified element in a sorted array and return its index if found, or -1 if not found. Example arrays and test cases are provided for each implementation.

Uploaded by

aj99883355
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as ODT, PDF, TXT or read online on Scribd
You are on page 1/ 4

Recusive binary search

#include <stdio.h>

int binarySearchRecursive(int arr[], int low, int high, int x) {

if (high >= low) {

int mid = low + (high - low) / 2;

if (arr[mid] == x)

return mid;

if (arr[mid] > x)

return binarySearchRecursive(arr, low, mid - 1, x);

return binarySearchRecursive(arr, mid + 1, high, x);

return -1;

int main() {

int arr[] = {2, 5, 8, 12, 16, 23, 38, 56, 72, 91};

int x = 23;

int n = sizeof(arr) / sizeof(arr[0]);

int result = binarySearchRecursive(arr, 0, n - 1, x);

if (result == -1)

printf("Element not found in the array");


else

printf("Element found at index %d", result);

return 0;

Non Recursive

#include <stdio.h>

int binarySearch(int arr[], int low, int high, int x)

{
while (low <= high) {

int mid = low + (high - low) / 2;

// Check if x is present at mid

if (arr[mid] == x)

return mid;

// If x greater, ignore left half

if (arr[mid] < x)

low = mid + 1;

// If x is smaller, ignore right half

else

high = mid - 1;

return -1;

// Driver code

int main(void)

int arr[] = { 2, 3, 4, 10, 40 };

int n = sizeof(arr) / sizeof(arr[0]);

int x = 10;

int result = binarySearch(arr, 0, n - 1, x);

if(result == -1) printf("Element is not present in array");


else printf("Element is present at index %d",result);

You might also like