Created
June 22, 2017 11:30
-
-
Save isurum/25df10995f277561078dd1241750ea8a to your computer and use it in GitHub Desktop.
Binary Search Implementation Using Java
This file contains hidden or 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
package uk.co.stableweb; | |
public class BinarySearch { | |
public static void main(String[] args) { | |
// Create an array | |
int[] array = {1, 3, 5, 7, 9, 11, 15, 17, 19}; | |
// Initially lowest index is 0 | |
int lowestIndex = 0; | |
// Initially highest value is the length of array | |
int highestIndex = array.length; | |
// Value to be searched. | |
int searchValue = 3; | |
// Run the while loop until highest value is bigger than lowest value | |
while(highestIndex >= lowestIndex){ | |
// Compute the middle index | |
int middleIndex = (lowestIndex + highestIndex) / 2; | |
// If the middle item matches to the search value print it and break the loop. | |
if(array[middleIndex] == searchValue){ | |
System.out.println("Element is at " + middleIndex); | |
break; | |
} | |
// If the search value is larger than the middle value add 1 to the middle value and | |
// assign to lowest value | |
if(array[middleIndex] < searchValue){ | |
lowestIndex = middleIndex + 1; | |
} | |
// If the search value is smaller than the middle value reduce 1 from middle value and | |
// assign it to highest value | |
if(array[middleIndex] > searchValue){ | |
highestIndex = middleIndex - 1; | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment