From da3273af6ebe6c3223e5206b0a9ad4a724c485e3 Mon Sep 17 00:00:00 2001 From: Shivang Sarawagi Date: Wed, 16 Aug 2017 11:26:42 +0530 Subject: [PATCH] Binary Search algorithm (#2448) --- .../com/baeldung/algorithms/BinarySearch.java | 26 +++++++++++++++++++ .../java/algorithms/BinarySearchTest.java | 14 ++++++++++ 2 files changed, 40 insertions(+) create mode 100644 algorithms/src/main/java/com/baeldung/algorithms/BinarySearch.java create mode 100644 algorithms/src/test/java/algorithms/BinarySearchTest.java diff --git a/algorithms/src/main/java/com/baeldung/algorithms/BinarySearch.java b/algorithms/src/main/java/com/baeldung/algorithms/BinarySearch.java new file mode 100644 index 0000000000..be4a9e578a --- /dev/null +++ b/algorithms/src/main/java/com/baeldung/algorithms/BinarySearch.java @@ -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; + } +} diff --git a/algorithms/src/test/java/algorithms/BinarySearchTest.java b/algorithms/src/test/java/algorithms/BinarySearchTest.java new file mode 100644 index 0000000000..d53b074cc4 --- /dev/null +++ b/algorithms/src/test/java/algorithms/BinarySearchTest.java @@ -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()); + } + +}