Skip to content

Commit

Permalink
binarySearch on sorted arrays and sorted lists
Browse files Browse the repository at this point in the history
  • Loading branch information
kvr000 committed Aug 26, 2024
1 parent ec4f545 commit 4c6002d
Show file tree
Hide file tree
Showing 4 changed files with 412 additions and 0 deletions.
109 changes: 109 additions & 0 deletions src/main/java/org/apache/commons/lang3/ArrayUtils.java
Original file line number Diff line number Diff line change
Expand Up @@ -1432,6 +1432,115 @@ public static <T> T arraycopy(final T source, final int sourcePos, final T dest,
return dest;
}

/**
* Searches element in array sorted by key.
*
* @param array
* array sorted by key field
* @param key
* key to search for
* @param keyExtractor
* function to extract key from element
* @param comparator
* comparator for keys
*
* @return
* index of the search key, if it is contained in the array within specified range; otherwise,
* (-first_greater - 1). The first_greater is the index of lowest greater element in the list - if all elements
* are lower, the first_greater is defined as toIndex.
*
* @param <T>
* type of array element
* @param <K>
* type of key
*/
public static <K, T> int binarySearch(
T[] array,
K key,
Function<T, K> keyExtractor, Comparator<? super K> comparator
) {
return binarySearch0(array, 0, array.length, key, keyExtractor, comparator);
}

/**
* Searches element in array sorted by key, within range fromIndex - toIndex (inclusive - exclusive).
*
* @param array
* array sorted by key field
* @param fromIndex
* start index
* @param toIndex
* end index (exclusive)
* @param key
* key to search for
* @param keyExtractor
* function to extract key from element
* @param comparator
* comparator for keys
*
* @return
* index of the search key, if it is contained in the array within specified range; otherwise,
* (-first_greater - 1). The first_greater is the index of lowest greater element in the list - if all elements
* are lower, the first_greater is defined as toIndex.
*
* @throws ArrayIndexOutOfBoundsException
* when fromIndex or toIndex is out of array range
* @throws IllegalArgumentException
* when fromIndex is greater than toIndex
*
* @param <T>
* type of array element
* @param <K>
* type of key
*/
public static <T, K> int binarySearch(
T[] array,
int fromIndex, int toIndex,
K key,
Function<T, K> keyExtractor, Comparator<? super K> comparator
) {
if (fromIndex > toIndex) {
throw new IllegalArgumentException(
"fromIndex(" + fromIndex + ") > toIndex(" + toIndex + ")");
}
if (fromIndex < 0) {
throw new ArrayIndexOutOfBoundsException(fromIndex);
}
if (toIndex > array.length) {
throw new ArrayIndexOutOfBoundsException(toIndex);
}

return binarySearch0(array, fromIndex, toIndex, key, keyExtractor, comparator);
}

// common implementation for binarySearch methods, with same semantics:
private static <T, K> int binarySearch0(
T[] array,
int fromIndex, int toIndex,
K key,
Function<T, K> keyExtractor, Comparator<? super K> comparator
) {
int l = fromIndex;
int h = toIndex - 1;

while (l <= h) {
final int m = (l + h) >>> 1; // unsigned shift to avoid overflow
final K value = keyExtractor.apply(array[m]);
final int c = comparator.compare(value, key);
if (c < 0) {
l = m + 1;
} else if (c > 0) {
h = m - 1;
} else {
// 0, found
return m;
}
}

// not found, the l points to the lowest higher match:
return -l - 1;
}

/**
* Clones an array or returns {@code null}.
* <p>
Expand Down
110 changes: 110 additions & 0 deletions src/main/java/org/apache/commons/lang3/SortedListUtils.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,110 @@
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.lang3;

import java.util.Comparator;
import java.util.List;
import java.util.function.Function;


/**
* Operations on sorted {@link List}.
*/
public class SortedListUtils {
/**
* Finds element in sorted list.
*
* @param list
* list sorted by key field
* @param key
* key to search for
* @param keyExtractor
* function to extract key from element
* @param comparator
* comparator for keys
*
* @return
* index of the search key, if it is contained in the list within specified range; otherwise,
* (-first_greater - 1). The first_greater is the index of lowest greater element in the list - if all elements
* are lower, the first_greater is defined as toIndex.
*
* @param <T>
* type of list element
* @param <K>
* type of key
*/
public static <K, T> int binarySearch(
List<T> list,
K key,
Function<T, K> keyExtractor, Comparator<? super K> comparator
) {
return binarySearch(list, 0, list.size(), key, keyExtractor, comparator);
}

/**
* Finds element in sorted list, within range fromIndex - toIndex (inclusive - exclusive).
*
* @param list
* list sorted by key field
* @param fromIndex
* start index
* @param toIndex
* end index (exclusive)
* @param key
* key to search for
* @param keyExtractor
* function to extract key from element
* @param comparator
* comparator for keys
*
* @return
* index of the search key, if it is contained in the list within specified range; otherwise,
* (-first_greater - 1). The first_greater is the index of lowest greater element in the list - if all elements
* are lower, the first_greater is defined as toIndex.
*
* @param <T>
* type of array element
* @param <K>
* type of key
*/
public static <T, K> int binarySearch(
List<T> list,
int fromIndex, int toIndex,
K key,
Function<T, K> keyExtractor, Comparator<? super K> comparator
) {
int l = fromIndex;
int h = toIndex - 1;

while (l <= h) {
int m = (l + h) >>> 1; // unsigned shift to avoid overflow
K value = keyExtractor.apply(list.get(m));
int c = comparator.compare(value, key);
if (c < 0) {
l = m + 1;
} else if (c > 0) {
h = m - 1;
} else {
// 0, found
return m;
}
}

// not found, the l points to the lowest higher match:
return -l - 1;
}
}
109 changes: 109 additions & 0 deletions src/test/java/org/apache/commons/lang3/ArrayUtilsBinarySearchTest.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,109 @@
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.lang3;

import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrowsExactly;

import java.util.stream.IntStream;

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

/**
* Unit tests {@link ArrayUtils} binarySearch functions.
*/
public class ArrayUtilsBinarySearchTest extends AbstractLangTest {

@Test
public void binarySearch_whenLowHigherThanEnd_throw() {
final Data[] list = createList(0, 1);
assertThrowsExactly(IllegalArgumentException.class, () -> ArrayUtils.binarySearch(list, 1, 0, 0, Data::getValue, Integer::compare));
}

@Test
public void binarySearch_whenLowNegative_throw() {
final Data[] list = createList(0, 1);
assertThrowsExactly(ArrayIndexOutOfBoundsException.class, () -> ArrayUtils.binarySearch(list, -1, 0, 0, Data::getValue, Integer::compare));
}

@Test
public void binarySearch_whenEndBeyondLength_throw() {
final Data[] list = createList(0, 1);
assertThrowsExactly(ArrayIndexOutOfBoundsException.class, () -> ArrayUtils.binarySearch(list, 0, 3, 0, Data::getValue, Integer::compare));
}

@Test
public void binarySearch_whenEmpty_returnM1() {
final Data[] list = createList();
final int found = ArrayUtils.binarySearch(list, 0, Data::getValue, Integer::compare);
assertEquals(-1, found);
}

@Test
public void binarySearch_whenExists_returnIndex() {
final Data[] list = createList(0, 1, 2, 4, 7, 9, 12, 15, 17, 19, 25);
final int found = ArrayUtils.binarySearch(list, 9, Data::getValue, Integer::compare);
assertEquals(5, found);
}

@Test
public void binarySearch_whenNotExists_returnMinusInsertion() {
final Data[] list = createList(0, 1, 2, 4, 7, 9, 12, 15, 17, 19, 25);
final int found = ArrayUtils.binarySearch(list, 8, Data::getValue, Integer::compare);
assertEquals(-6, found);
}

@Test
public void binarySearch_whenNotExistsBeginning_returnMinus1() {
final Data[] list = createList(0, 1, 2, 4, 7, 9, 12, 15, 17, 19, 25);
final int found = ArrayUtils.binarySearch(list, -3, Data::getValue, Integer::compare);
assertEquals(-1, found);
}

@Test
public void binarySearch_whenNotExistsEnd_returnMinusLength() {
final Data[] list = createList(0, 1, 2, 4, 7, 9, 12, 15, 17, 19, 25);
final int found = ArrayUtils.binarySearch(list, 29, Data::getValue, Integer::compare);
assertEquals(-(list.length + 1), found);
}

@Test
@Timeout(10)
public void binarySearch_whenUnsorted_dontInfiniteLoop() {
final Data[] list = createList(7, 1, 4, 9, 11, 8);
final int found = ArrayUtils.binarySearch(list, 10, Data::getValue, Integer::compare);
}

private Data[] createList(int... values) {
return IntStream.of(values).mapToObj(Data::new)
.toArray(Data[]::new);
}

static class Data {

private final int value;

Data(int value) {
this.value = value;
}

public int getValue() {
return value;
}
}
}
Loading

0 comments on commit 4c6002d

Please sign in to comment.