Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Implement iterative binary search #1255

Closed
wants to merge 1 commit into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
38 changes: 38 additions & 0 deletions src/main/java/com/search/IterativeBinarySearch.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
package com.search;

/**
* Binary search is an algorithm which finds the position of a target value within a sorted array
* <p>
* Worst-case performance O(log n)
* Best-case performance O(1)
* Average performance O(log n)
* Worst-case space complexity O(1)
*/
public final class IterativeBinarySearch {

/**
* @param array a sorted array
* @param key the key to search in array
* @return the index of key in the array or -1 if not found
*/
public static <T extends Comparable<T>> int find(T[] array, T key) {
int left = 0;
int right = array.length - 1;

while (left <= right) {
int middle = (left + right) / 2;
int compareTo = key.compareTo(array[middle]);

if (compareTo == 0) {
return middle;
} else if (compareTo < 0) {
right = --middle;
} else {
left = ++middle;
}
}

return -1;
}

}
26 changes: 26 additions & 0 deletions src/test/java/com/search/IterativeBinarySearchTest.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
package com.search;

import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;

public class IterativeBinarySearchTest {

@Test
void testIterativeBinarySearch() {
Integer[] arr1 = {1, 2, 3, 5, 8, 13, 21, 34, 55};
Assertions.assertEquals(2, IterativeBinarySearch.find(arr1, 3), "Incorrect index");
Assertions.assertEquals(0, IterativeBinarySearch.find(arr1, 1), "Incorrect index");
Assertions.assertEquals(8, IterativeBinarySearch.find(arr1, 55), "Incorrect index");
Assertions.assertEquals(-1, IterativeBinarySearch.find(arr1, -2), "Incorrect index");
Assertions.assertEquals(-1, IterativeBinarySearch.find(arr1, 4), "Incorrect index");

String[] arr2 = {"A", "B", "C", "D"};
Assertions.assertEquals(2, IterativeBinarySearch.find(arr2, "C"), "Incorrect index");
Assertions.assertEquals(1, IterativeBinarySearch.find(arr2, "B"), "Incorrect index");
Assertions.assertEquals(-1, IterativeBinarySearch.find(arr2, "F"), "Incorrect index");

String[] arr3 = {};
Assertions.assertEquals(-1, IterativeBinarySearch.find(arr3, ""), "Incorrect index");
}

}