Binary search iterative and recursive approach GFG
package com.company;
public class Searching {
// linear search
public static int searching(int[] array, int x) {
int n = array.length;
for(int i = 0; i < n; i++) {
if(array[i] == x) {
return i;
}
}
return -1;
}
// Binary search --> using the fact that the array is sorted
public static int binarySearching(int[] arr, int x) {
int n = arr.length;
int low = 0; int high = n - 1;
while(low <= high) {
int mid =(low + high) / 2;
if(arr[mid] == x){
return mid;
}
else if (arr[mid] < x) {
low = mid + 1;
}
else {
high = mid - 1;
}
}
return -1;
}
// Binary search using recursion
public static int binary(int[] arr, int x, int low, int high) {
int n = arr.length;
int mid = (low + high) / 2;
if( low > high){
return -1;
}
if(arr[mid] == x) {
return mid;
}
else if(arr[mid] > x){
return binary(arr, x, low, mid - 1);
}
else{
return binary(arr, x, mid + 1, high);
}
}
public static void main(String[] args) {
// write your code here
int[] arr = {10,30,40,50,60,90};
System.out.println(binary(arr, -90, 0, 5));
}
}
Comments
Post a Comment