Binary Search algorithm (#2448)

This commit is contained in:
Shivang Sarawagi 2017-08-16 11:26:42 +05:30 committed by maibin
parent 5d20115b41
commit da3273af6e
2 changed files with 40 additions and 0 deletions

View File

@ -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;
}
}

View File

@ -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());
}
}