Last active
July 18, 2021 07:38
-
-
Save mansi7babbar/380f67d421bebfcd95201de181b21b4b to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class BinarySearch | |
{ | |
public static int binarySearchRecursive(int[] list, int first, int last, int key) | |
{ | |
if(first >= last) | |
{ | |
return -1; | |
} | |
int middle = first + (last - first) / 2; | |
if(list[middle] == key) | |
{ | |
return middle; | |
} | |
else if(list[middle] < key) | |
{ | |
first = middle + 1; | |
return binarySearchRecursive(list, first, last, key); | |
} | |
else | |
{ | |
last = middle - 1; | |
return binarySearchRecursive(list, first, last, key); | |
} | |
} | |
public static void main(String[] args) | |
{ | |
int[] list = {10, 14, 19, 26, 27, 31, 33, 35, 42, 44}; | |
int element = 31; | |
int result = binarySearchRecursive(list, 0, list.length - 1, element); | |
if(result == -1) | |
{ | |
System.out.println("The element does not exist in the list"); | |
} | |
else | |
{ | |
System.out.println("The element found at index : " + result); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment