The following code shows a C Program for Recursive Binary Search.
// C Program for Recursive Binary Search
#include <stdio.h>
void BubbleSort(int arr[], int Length);
void swap(int arr[], int m, int n);
int RecursiveBinarySearch(int a[], int min, int max, int t)
{
int mid = (min + max) / 2;
if (a[mid] == t)
{
return mid;
}
if (a[mid] > t)
{
return RecursiveBinarySearch(a, min, mid - 1, t);
}
if (max < min) return -1;
return RecursiveBinarySearch(a, mid + 1, max, t);
}
void BubbleSort(int arr[], int Length)
{
int i, j;
for(i=0;i<Length-1;i++)
{
for(j=0;j<Length-i-1;j++)
{
if (arr[j] > arr[j + 1])
swap(arr, j, j+1);
}
}
}
void swap(int arr[], int m, int n)
{
int t = arr[m];
arr[m] = arr[n];
arr[n] = t;
}
int main()
{
int i, p, elements_count, pos;
int myarray[] = {78, 1, 6, 37, 96, 567, 123, 579, 23, 8, 18, 28, 58, 45, 2, 76};
elements_count=sizeof(myarray)/sizeof(int);
printf("Unsorted Array...");
for(i=0;i<elements_count;i++)
printf("%d ", myarray[i]);
printf("\n\n");
BubbleSort(myarray, elements_count);
printf("Sorted Array...");
for(i=0;i<elements_count;i++)
printf("%d ", myarray[i]);
printf("\n\n");
printf("Enter the target value to search: ");
scanf("%d", &p);
pos = RecursiveBinarySearch(myarray, 0, elements_count - 1, p);
if(pos!=-1)
printf("Target found at index %d", pos);
else
printf("Target not found!");
return 0;
}
Output
Unsorted Array…78 1 6 37 96 567 123 579 23 8 18 28 58 45 2 76
Sorted Array…1 2 6 8 18 23 28 37 45 58 76 78 96 123 567 579
Enter the target value to search: 57
Target not found!
Unsorted Array…78 1 6 37 96 567 123 579 23 8 18 28 58 45 2 76
Sorted Array…1 2 6 8 18 23 28 37 45 58 76 78 96 123 567 579
Enter the target value to search: 96
Target found at index 12
Further Reading
50+ C Programming Interview Questions and Answers
C Program to Find Factorial of a Number
- AI
- Android
- Angular
- ASP.NET
- Augmented Reality
- AWS
- Bioinformatics
- Biometrics
- Blockchain
- Bootstrap
- C
- C#
- C++
- Cloud Computing
- Competitions
- Courses
- CSS
- Cyber Security
- Data Science
- Data Structures and Algorithms
- Data Visualization
- Datafication
- Deep Learning
- DevOps
- Digital Forensic
- Digital Trust
- Digital Twins
- Django
- Docker
- Dot Net Framework
- Drones
- Elasticsearch
- ES6
- Extended Reality
- Flutter and Dart
- Full Stack Development
- Git
- Go
- HTML
- Image Processing
- IoT
- IT
- Java
- JavaScript
- Kotlin
- Latex
- Machine Learning
- MEAN Stack
- MERN Stack
- Microservices
- MongoDB
- NodeJS
- PHP
- Power Bi
- Projects
- Python
- Quantum Computing
- React
- Robotics
- Rust
- Scratch 3.0
- Shell Script
- Smart City
- Software
- Solidity
- SQL
- SQLite
- Tecgnology
- Tkinter
- TypeScript
- VB.NET
- Virtual Reality
- Web Designing
- WebAssembly
- XML