Skip to content

Refactoring BinaryInsertionSort according to common SortAlgorithm approach #5239

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

Merged
merged 8 commits into from
Jun 19, 2024
Original file line number Diff line number Diff line change
@@ -1,17 +1,17 @@
package com.thealgorithms.sorts;

public class BinaryInsertionSort {
public class BinaryInsertionSort implements SortAlgorithm {

// Binary Insertion Sort method
public int[] binaryInsertSort(int[] array) {
public <T extends Comparable<T>> T[] sort(T[] array) {
for (int i = 1; i < array.length; i++) {
int temp = array[i];
T temp = array[i];
int low = 0;
int high = i - 1;

while (low <= high) {
final int mid = (low + high) >>> 1;
if (temp < array[mid]) {
if (temp.compareTo(array[mid]) < 0) {
high = mid - 1;
} else {
low = mid + 1;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,22 +6,22 @@

class BinaryInsertionSortTest {

BinaryInsertionSort bis = new BinaryInsertionSort();
BinaryInsertionSort binaryInsertionSort = new BinaryInsertionSort();

@Test
// valid test case
public void binaryInsertionSortTestNonDuplicate() {
int[] array = {1, 0, 2, 5, 3, 4, 9, 8, 10, 6, 7};
int[] expResult = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
int[] actResult = bis.binaryInsertSort(array);
Integer[] array = {1, 0, 2, 5, 3, 4, 9, 8, 10, 6, 7};
Integer[] expResult = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
Integer[] actResult = binaryInsertionSort.sort(array);
assertArrayEquals(expResult, actResult);
}

@Test
public void binaryInsertionSortTestDuplicate() {
int[] array = {1, 1, 1, 5, 9, 8, 7, 2, 6};
int[] expResult = {1, 1, 1, 2, 5, 6, 7, 8, 9};
int[] actResult = bis.binaryInsertSort(array);
Integer[] array = {1, 1, 1, 5, 9, 8, 7, 2, 6};
Integer[] expResult = {1, 1, 1, 2, 5, 6, 7, 8, 9};
Integer[] actResult = binaryInsertionSort.sort(array);
assertArrayEquals(expResult, actResult);
}
}