Binary Search algorithm (#2448)
This commit is contained in:
parent
5d20115b41
commit
da3273af6e
|
@ -0,0 +1,26 @@
|
|||
public class BinarySearch {
|
||||
|
||||
public int runBinarySearch() {
|
||||
int[] sortedArray = { 0, 1, 2, 3, 4, 5, 5, 6, 7, 8, 9, 9 };
|
||||
int key = 6;
|
||||
|
||||
int low = 0;
|
||||
int high = sortedArray.length - 1;
|
||||
int index = Integer.MAX_VALUE;
|
||||
|
||||
while (low <= high) {
|
||||
|
||||
int mid = (low + high) / 2;
|
||||
|
||||
if (sortedArray[mid] < key) {
|
||||
low = mid + 1;
|
||||
} else if (sortedArray[mid] > key) {
|
||||
high = mid - 1;
|
||||
} else if (sortedArray[mid] == key) {
|
||||
index = mid;
|
||||
break;
|
||||
}
|
||||
}
|
||||
return index;
|
||||
}
|
||||
}
|
|
@ -0,0 +1,14 @@
|
|||
import org.junit.Assert;
|
||||
import org.junit.Test;
|
||||
|
||||
|
||||
public class BinarySearchTest {
|
||||
|
||||
@Test
|
||||
public void givenASortedArrayOfIntegers_whenBinarySearchRunForANumber_thenGetIndexOfTheNumber() {
|
||||
BinarySearch binSearch = new BinarySearch();
|
||||
int expectedIndexForSearchKey = 7;
|
||||
Assert.assertEquals(expectedIndexForSearchKey, binSearch.runBinarySearch());
|
||||
}
|
||||
|
||||
}
|
Loading…
Reference in New Issue