Created
July 18, 2021 15:09
-
-
Save mansi7babbar/0a57810c859973e90f8fc522a67c3fdd 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 BinarySearchAlgorithm | |
{ | |
public static int recursiveBinarySearch(int[] list, int low, int high, int key) | |
{ | |
if( low >= high) | |
{ | |
return -1; | |
} | |
int middle = low + (high - low) / 2; | |
if(list[middle] == key) | |
{ | |
return middle; | |
} | |
else if(list[middle] < key) | |
{ | |
low = middle + 1; | |
return recursiveBinarySearch(list, low, high, key); | |
} | |
else | |
{ | |
high = middle - 1; | |
return recursiveBinarySearch(list, low, high, key); | |
} | |
} | |
public static int iterativeBinarySearch(int[] list, int low, int high, int key) | |
{ | |
while(low <= high) | |
{ | |
int middle = low + (high - low) / 2; | |
if(list[middle] == key) | |
{ | |
return middle; | |
} | |
else if(list[middle] < key) | |
{ | |
low = middle + 1; | |
} | |
else | |
{ | |
high = middle - 1; | |
} | |
} | |
return -1; | |
} | |
public static void main(String[] args) | |
{ | |
int[] list = {1, 3, 4, 6, 7, 9, 10, 11, 13}; | |
int recursiveBinarySearchResult = recursiveBinarySearch(list, 0, list.length - 1, 6); | |
if(recursiveBinarySearchResult == -1) | |
{ | |
System.out.println("The item does not exist in the list"); | |
} | |
else | |
{ | |
System.out.println("The item found at index : " + result); | |
} | |
int iterativeBinarySearchResult = iterativeBinarySearch(list, 0, list.length - 1, 12); | |
if(iterativeBinarySearchResult == -1) | |
{ | |
System.out.println("The item does not exist in the list"); | |
} | |
else | |
{ | |
System.out.println("The item found at index : " + result); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment