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,950 questions

51,892 answers

573 users

How to implement recursive binary search in C

2 Answers

0 votes
#include <stdio.h> 
  
int recursive_binary_search(int arr[], int left, int right, int to_find) { 
    if (right >= left) { 
        int mid = left + (right - left) / 2; 

        if (arr[mid] == to_find) 
            return mid; 
  
        if (arr[mid] > to_find) 
            return recursive_binary_search(arr, left, mid - 1, to_find); 
  
        return recursive_binary_search(arr, mid + 1, right, to_find); 
    } 

    return -1; 
} 
  
int main(void) 
{ 
    int arr[] = { 2, 3, 6, 7, 12, 15, 17, 19 }; 
    int len = sizeof(arr) / sizeof(arr[0]); 
    int to_find = 7; 
	
    int i = recursive_binary_search(arr, 0, len - 1, to_find); 
	
    (i == -1) ? printf("not found\n") : printf("Found at index: %d\n", i); 
	
    return 0; 
} 
 
 
 
/*
run:
 
Found at index: 3

*/

 



answered Aug 4, 2019 by avibootz
0 votes
#include <stdio.h> 
  
int recursive_binary_search(int arr[], int left, int right, int to_find) {
   int mid = (left + right) / 2;
   if (left > right) return -1;
   if (arr[mid] == to_find) return mid;
   
   if (arr[mid] < to_find) 
		return recursive_binary_search(arr, mid + 1, right, to_find);
   else 
		return recursive_binary_search(arr, left, mid-1, to_find);
} 
  
int main(void) 
{ 
    int arr[] = { 2, 3, 6, 7, 12, 15, 17, 19 }; 
    int len = sizeof(arr) / sizeof(arr[0]); 
    int to_find = 7; 
	
    int i = recursive_binary_search(arr, 0, len - 1, to_find); 
	
    (i == -1) ? printf("not found\n") : printf("Found at index: %d\n", i); 
	
    return 0; 
} 
 
 
 
/*
run:
 
Found at index: 3

*/

 



answered Aug 4, 2019 by avibootz

Related questions

2 answers 192 views
1 answer 78 views
1 answer 106 views
1 answer 85 views
1 answer 90 views
1 answer 79 views
1 answer 82 views
...