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

Open
wants to merge 1 commit into
base: Development
from
Open
Changes from all commits
Commits
File filter...
Filter file types
Jump to…
Jump to file
Failed to load files.

Always

Just for now

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

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

}
ProTip! Use n and p to navigate between commits in a pull request.
You can’t perform that action at this time.