Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Buy a domain name - Register cheap domain names from $0.99 - Namecheap

Scalable Hosting That Grows With You

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Semrush - keyword research tool

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

39,948 questions

51,890 answers

573 users

How to implement binary search using recursion in C

1 Answer

0 votes
#include <stdio.h>

#define LEN 10

int binary_search(int arr[], int n, int start, int end);

int main(void)
{
	int idx, start, end;
	int arr[LEN] = { 2, 5, 7, 8, 9, 12, 45, 78, 98, 100 };

	start = 0;
	end = LEN - 1;

	idx = binary_search(arr, 45, start, end);

	if (idx != -1) 
		printf("Found: arr[%d] = %d", idx, arr[idx]);
    else
		printf("Not Found");

    return 0;
}
int binary_search(int arr[], int n, int start, int end) 
{
   int mid;
 
   if (start > end)
       return -1;
 
   mid = (start + end) / 2;
 
   if (n == arr[mid]) 
       return (mid);
   else if (n < arr[mid]) 
			binary_search(arr, n, start, mid - 1);
		else 
			binary_search(arr, n, mid + 1, end);
}
  
    
/*
      
run:

Found: arr[6] = 45

*/

 



answered Jan 30, 2016 by avibootz

Related questions

1 answer 167 views
167 views asked Jan 18, 2022 by avibootz
1 answer 146 views
2 answers 165 views
1 answer 193 views
1 answer 164 views
1 answer 149 views
...