0% found this document useful (0 votes)
12 views2 pages

Binary Search Recursive

This document contains a C program that implements a recursive binary search algorithm. It searches for a target value within a sorted array and returns the index of the target if found, or -1 if not found. The main function demonstrates the usage of the binary search function with a sample array and target value.

Uploaded by

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

Binary Search Recursive

This document contains a C program that implements a recursive binary search algorithm. It searches for a target value within a sorted array and returns the index of the target if found, or -1 if not found. The main function demonstrates the usage of the binary search function with a sample array and target value.

Uploaded by

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

// Recursive implementation of the binary search algorithm to return

#include <stdio.h>

int binarySearch(int nums[], int low, int high, int target)


{
if (low > high) {
return -1;
}
int mid = (low + high)/2;

if (target == nums[mid]) {
return mid;
}

else if (target < nums[mid]) {


return binarySearch(nums, low, mid - 1, target);
}

else {
return binarySearch(nums, mid + 1, high, target);
}
}

int main( )
{
int nums[] = { 2, 5, 6, 8, 9, 10 };
int target = 5;
int n = sizeof(nums)/sizeof(nums[0]);
int low = 0, high = n - 1;
int index = binarySearch(nums, low, high, target);

if (index != -1) {
printf("Element found at index %d", index);
}
else {
printf("Element not found in the array");
}

return 0;
}

You might also like