Add tests for the binary search implementation. (#110)

This commit is contained in:
Michael Mkwelele
2019-11-12 07:19:00 -08:00
committed by Aditya Bhargava
parent 184f80127c
commit 0377eab73c
2 changed files with 113 additions and 0 deletions

View File

@@ -0,0 +1,63 @@
package main;
public class BinarySearch {
public static void main(String[] args) {
int[] myList = {87, 21, 45, 93};
System.out.println(binarySearch(myList, 93));
System.out.println(binarySearch(myList, 16));
}
public static int binarySearch(int[] list, int item) {
if (isListEmpty(list)) {
return -1;
}
int low = 0;
int high = list.length - 1;
while (low <= high) {
int mid = (low + high) / 2;
int guess = list[mid];
if (guessEqualsItem(guess, item)) {
return mid;
} else if (guessGreaterThanItem(guess, item)) {
high = mid - 1;
} else if(guessLessThanItem(guess, item)) {
low = mid + 1;
}
}
return -1;
}
public static boolean isListEmpty(int[] myList) {
int listSize = myList.length;
if (listSize == 0) {
return true;
}
return false;
}
public static boolean guessEqualsItem(int guess, int item) {
if (guess != item) {
return false;
}
return true;
}
public static boolean guessGreaterThanItem(int guess, int item) {
if (guess < item) {
return false;
}
return true;
}
public static boolean guessLessThanItem(int guess, int item) {
if (guess > item) {
return false;
}
return true;
}
}

View File

@@ -0,0 +1,50 @@
package test;
import main.BinarySearch;
import org.junit.Assert;
import org.junit.Test;
public class BinarySearchTest {
@Test
public void testListIsEmpty() {
BinarySearch binarySearch = new BinarySearch();
int[] myList = {6, 9};
int[] emptyList = {};
Assert.assertEquals(false, binarySearch.isListEmpty(myList));
Assert.assertEquals(true, binarySearch.isListEmpty(emptyList));
}
@Test
public void testGuessEqualsItem() {
BinarySearch binarySearch = new BinarySearch();
Assert.assertEquals(true, binarySearch.guessEqualsItem(3, 3));
Assert.assertEquals(false, binarySearch.guessEqualsItem(0, 4));
}
@Test
public void testGuessIsLessThanItem() {
BinarySearch binarySearch = new BinarySearch();
Assert.assertEquals(true, binarySearch.guessLessThanItem(2, 7));
Assert.assertEquals(false, binarySearch.guessLessThanItem(6, 1));
}
@Test
public void testGuessGreaterThanItem() {
BinarySearch binarySearch = new BinarySearch();
Assert.assertEquals(true, binarySearch.guessGreaterThanItem(17, 12));
Assert.assertEquals(false, binarySearch.guessGreaterThanItem(13, 28));
}
@Test
public void testGivenListAndItemReturnIndexOfItem() {
BinarySearch binarySearch = new BinarySearch();
int[] testList = {1, 3, 5, 7, 9};
Assert.assertEquals(1, binarySearch.binarySearch(testList, 3));
Assert.assertEquals(-1, binarySearch.binarySearch(testList, 77));
}
}