// Binary Search implimentation in C (Recursive)
// Time Complexity : O(N)
// Space Complexity : O(1)
// Auxiliary Space Complexity : O(N) due to function call stack
#include<stdio.h>
int binarySearch(int arr[], int left, int right, int item){
if (right >= left){
// calculation of new mid
int mid = left + (right - left)/2;
// returns position where found
if (arr[mid] == item)
return mid;
// goes to recursive calls in left half
if (arr[mid] > item)
return binarySearch(arr, left, mid-1, item);
// goes to recursive calls in right half
else
return binarySearch(arr, mid+1, right, item);
}
// if element is not found we return -1
else
return -1;
}
int main(){
// array needs to be sorted to impliment binary search
int arr[8] = {10, 20, 30, 40, 50, 60, 70, 80};
int n = sizeof(arr) / sizeof(arr[0]);
int item = 70;
int position = binarySearch(arr, 0, n-1, item);
if(position == -1)
printf("%d Not Found",item);
else
printf("%d Found at index : %d",item, position);
}
// Binary Search implimentation in C++ (Recursive)
// Time Complexity : O(N)
// Space Complexity : O(1)
// Auxiliary Space Complexity : O(N) due to function call stack
#include<bits/stdc++.h>
using namespace std;
int binarySearch(int array[], int left, int right, int item){
if (right >= left){
// calculation of new mid
int mid = left + (right - left)/2;
// returns position where found
if (array[mid] == item)
return mid+1;
// goes to recursive calls in left half
if (array[mid] > item)
return binarySearch(array, left, mid-1, item);
// goes to recursive calls in right half
else
return binarySearch(array, mid+1, right, item);
}
// if element is not found we return -1
else
return -1;
}
int main(){
int array[10] = {3, 5, 7, 9, 12, 70, 16, 18, 19, 22};
int item = 70;
int position = binarySearch(array, 0, 10, item);
if(position == -1)
cout<<"Not Found";
else
cout << item << " Found at position : " << position;
}
// Binary Search implimentation in Java (Recursive)
// Time Complexity : O(N)
// Space Complexity : O(1)
// Auxiliary Space Complexity : O(N) due to function call stack
public class Main{
public static int binarySearch(int array[], int left, int right, int item){
if (right >= left){
// calculation of new mid
int mid = left + (right - left)/2;
// returns position where found
if (array[mid] == item)
return mid;
// goes to recursive calls in left half
if (array[mid] > item)
return binarySearch(array, left, mid-1, item);
// goes to recursive calls in right half
else
return binarySearch(array, mid+1, right, item);
}
// if element is not found we return -1
else
return -1;
}
public static void main(String args[]){
int[ ] array = {10, 20, 30, 40, 50, 60, 70, 80};
int item = 70;
int size = array.length;
int position = binarySearch(array, 0, size-1, item);
if(position == -1)
System.out.println("Element not found");
else
System.out.println(item + " found at position: " + position);
}
}
// Time complexity O(Log N)