Last active
July 18, 2021 07:41
-
-
Save mansi7babbar/3673fdaf4d1044b77d64ae04d05a3ef2 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 binarySearchIterative(int[] list, int first, int last, int key) | |
{ | |
while(first <= last) | |
{ | |
int middle = first + (last - first) / 2; | |
if(list[middle] == key) | |
{ | |
return middle; | |
} | |
else if(list[middle] < key) | |
{ | |
first = middle + 1; | |
} | |
else | |
{ | |
last = middle - 1; | |
} | |
} | |
return -1; | |
} | |
public static void main(String[] args) | |
{ | |
int[] list = {10, 14, 19, 26, 27, 31, 33, 35, 42, 44}; | |
int element = 31; | |
int result = binarySearchIterative(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