Skip to content

Commit da3273a

Browse files
techPacketsmaibin
authored andcommitted
Binary Search algorithm (eugenp#2448)
1 parent 5d20115 commit da3273a

2 files changed

Lines changed: 40 additions & 0 deletions

File tree

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
public class BinarySearch {
2+
3+
public int runBinarySearch() {
4+
int[] sortedArray = { 0, 1, 2, 3, 4, 5, 5, 6, 7, 8, 9, 9 };
5+
int key = 6;
6+
7+
int low = 0;
8+
int high = sortedArray.length - 1;
9+
int index = Integer.MAX_VALUE;
10+
11+
while (low <= high) {
12+
13+
int mid = (low + high) / 2;
14+
15+
if (sortedArray[mid] < key) {
16+
low = mid + 1;
17+
} else if (sortedArray[mid] > key) {
18+
high = mid - 1;
19+
} else if (sortedArray[mid] == key) {
20+
index = mid;
21+
break;
22+
}
23+
}
24+
return index;
25+
}
26+
}
Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
import org.junit.Assert;
2+
import org.junit.Test;
3+
4+
5+
public class BinarySearchTest {
6+
7+
@Test
8+
public void givenASortedArrayOfIntegers_whenBinarySearchRunForANumber_thenGetIndexOfTheNumber() {
9+
BinarySearch binSearch = new BinarySearch();
10+
int expectedIndexForSearchKey = 7;
11+
Assert.assertEquals(expectedIndexForSearchKey, binSearch.runBinarySearch());
12+
}
13+
14+
}

0 commit comments

Comments
 (0)