Taskcore
Search a sorted list
Also called binary search, bisect, find in a sorted array, lower bound, index of a value, search a sorted array.
Find the first index of a value in a sorted list of integers with a binary search, or give -1 when the value is not in the list.
- Evidence
- Code in 10 languages
Task
Find a value in a list of integers in ascending order. The function index_of(items, target) returns the first index of target, or -1 if no item is equal to it. For example, index_of([1, 3, 5, 7, 9], 5) is 2, and index_of([1, 3, 5, 7, 9], 4) is -1.
The list can have equal items. For index_of([1, 2, 2, 2, 3], 2), the result is 1, the first of the equal items. The list can be empty, and the items are 32-bit signed integers.
A binary search uses the order of the list. It compares the target with the middle item, and then searches only the half that can contain the target.
Solutions
| Language | Find the first index of target |
|---|---|
| Python | bisect_left(items, target), then a check of the item |
| JavaScript, TypeScript | a binary search loop for the first item that is not less than target |
| Java | the same loop; Arrays.binarySearch can give any equal item |
| C# | the same loop; Array.BinarySearch can give any equal item |
| Go | slices.BinarySearch(items, target), then a check of found |
| Rust | items.partition_point(|&x| x < target), then a check of the item |
| C | the same loop as JavaScript, with size_t indexes |
| C++ | std::ranges::lower_bound(items, target), then a check of the item |
| Bash | the same loop, with (( )) for the comparisons |
- The loop. The loop keeps two indexes,
loandhi. Each item beforelois less than the target, and each item fromhiis not less than the target. At the end,lois the first index of an item that is not less than the target. The middle index islo + (hi - lo) / 2, becauselo + hican be too large for the integer type. - Python. For
bisect_left, "If x is already present in a, the insertion point will be before (to the left of) any existing entries"1. Thus the result is the first of the equal items. - Java. "If the array contains multiple elements with the specified value, there is no guarantee which one will be found."2 Thus the solution uses its own loop.
- Go.
slices.BinarySearch"returns the earliest position where target is found, or the position where target would appear in the sort order"3. - C. For
bsearch, "it is unspecified which element the function will return as the result"4 when there are equal items. Thus the solution uses its own loop.
Edge cases
The cases are in cases/basic.jsonl and cases/edge.jsonl.
firstandlast: the target can be at index 0 or at the last index.missing,belowandabove: a target that is not in the list gives -1. It can be between two items, before the first item or after the last item.empty: an empty list gives -1 for each target.single-hitandsingle-miss: a list of one item.duplicatesandall-same: with equal items, the result is the first index.negative: the list can have negative items.extremesandmin-target: the items and the target can be -2147483648 or 2147483647.
Pitfalls
- Python bisect_left gives an insertion point. It does not tell if the target is in the list. In the example,
bisect_left([1, 3, 5], 4)is 2, but 4 is not in the list. Check the item at the index:
from bisect import bisect_left
items = [1, 3, 5]
i = bisect_left(items, 4)
print(i)
print(i if i < len(items) and items[i] == 4 else -1)
2
-1
- JavaScript indexOf is a linear search, and it does not find NaN. JavaScript has no binary search function for arrays.
indexOf"compares searchElement to elements of the array using strict equality"5, so it gives -1 forNaN. UsefindIndex(Number.isNaN):
const items = [1, NaN, 3];
console.log(items.indexOf(NaN));
console.log(items.findIndex(Number.isNaN));
-1
1
- Java binarySearch gives a negative number for a missing key. The result is "(-(insertion point) - 1)"2, not -1. In the example, the result for 4 is -3:
import java.util.Arrays;
public class Main {
public static void main(String[] args) {
int[] items = {1, 3, 5};
int r = Arrays.binarySearch(items, 4);
System.out.println(r);
System.out.println(r >= 0 ? r : -1);
}
}
-3
-1
- C# BinarySearch gives a bitwise complement for a missing value. The result is "the bitwise complement of the index of the first element that is larger than value"6.
~rgives the index back:
using System;
int[] items = [1, 3, 5];
int r = Array.BinarySearch(items, 4);
Console.WriteLine(r);
Console.WriteLine(~r);
-3
2
- Go BinarySearch gives a position also for a missing target. It "also returns a bool saying whether the target is really found in the slice"3. Check the bool:
package main
import (
"fmt"
"slices"
)
func main() {
i, found := slices.BinarySearch([]int{1, 3, 5}, 4)
fmt.Println(i, found)
}
2 false
- Rust binary_search can give any of the equal items. "If there are multiple matches, then any one of the matches could be returned."7 Also, "The index is chosen deterministically, but is subject to change in future versions of Rust"7. For the first index, use
partition_point:
fn main() {
let items = [1, 2, 2, 2, 3];
// Any of the indexes 1, 2 and 3 is a correct result of binary_search.
let r = items.binary_search(&2);
println!("{}", matches!(r, Ok(1..=3)));
println!("{}", items.partition_point(|&x| x < 2));
}
true
1
- C bsearch gives a pointer. It gives
NULLfor a missing key. For the index, subtract the start of the array from the pointer. The compare function must not subtract the two integers, because the subtraction can overflow:
#include <stdio.h>
#include <stdlib.h>
static int cmp(const void *a, const void *b) {
int x = *(const int *)a;
int y = *(const int *)b;
return (x > y) - (x < y);
}
int main(void) {
int items[] = {1, 3, 5, 7};
size_t n = sizeof items / sizeof items[0];
int key = 5;
const int *p = bsearch(&key, items, n, sizeof items[0], cmp);
printf("%td\n", p - items);
key = 4;
p = bsearch(&key, items, n, sizeof items[0], cmp);
printf("%s\n", p == NULL ? "NULL" : "found");
return 0;
}
2
NULL
- C++ binary_search gives only a bool. The result is "true if an element equivalent to value exists, false otherwise"8. For the index, use
std::lower_bound:
#include <algorithm>
#include <iostream>
#include <vector>
int main() {
std::vector<int> v{1, 2, 2, 2, 3};
std::cout << std::boolalpha << std::binary_search(v.begin(), v.end(), 2) << '\n';
auto it = std::lower_bound(v.begin(), v.end(), 2);
std::cout << (it - v.begin()) << '\n';
}
true
1
- Bash [[ < ]] compares text. The operators "sort lexicographically using the current locale"9. In the example,
[[ 10 < 9 ]]is true. Use(( ))to compare numbers:
if [[ 10 < 9 ]]; then
echo "text: 10 < 9"
fi
if ((10 < 9)); then
echo "number: 10 < 9"
else
echo "number: 10 >= 9"
fi
text: 10 < 9
number: 10 >= 9
Related tasks
- Sort a list: sort the list before the search.
- Check whether a list contains a value: test for a value in a list that is not sorted.
- Find the largest element: find a value without a sorted list.
- Filter a list: find all the items that pass a test.
- Rotate a list: a rotated sorted list is not sorted, so a binary search does not work on it.
Code
The build runs the native tests of each language in a pinned toolchain.
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/search-a-sorted-list/.
from bisect import bisect_left
def index_of(items: list[int], target: int) -> int:
"""Return the first index of target in the sorted list items, or -1."""
# bisect_left gives the first index i with items[i] >= target.
i = bisect_left(items, target)
if i < len(items) and items[i] == target:
return i
return -1
test_index_of.py 29 lines
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/search-a-sorted-list/.
import pytest
from index_of import index_of
CASES = {
"middle": ([1, 3, 5, 7, 9], 5, 2),
"first": ([1, 3, 5, 7, 9], 1, 0),
"last": ([1, 3, 5, 7, 9], 9, 4),
"missing": ([1, 3, 5, 7, 9], 4, -1),
"below": ([1, 3, 5], 0, -1),
"above": ([1, 3, 5], 6, -1),
"empty": ([], 1, -1),
"single-hit": ([7], 7, 0),
"single-miss": ([7], 8, -1),
"duplicates": ([1, 2, 2, 2, 3], 2, 1),
"all-same": ([4, 4, 4, 4], 4, 0),
"negative": ([-9, -5, -1, 0], -5, 1),
"extremes": ([-2147483648, 0, 2147483647], 2147483647, 2),
"min-target": ([-2147483648, 0, 2147483647], -2147483648, 0),
}
@pytest.mark.parametrize("name", CASES)
def test_index_of(name):
items, target, want = CASES[name]
assert index_of(items, target) == want
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/search-a-sorted-list/.
#include "index_of.hpp"
#include <algorithm>
long index_of(std::span<const int> items, int target) {
// lower_bound gives the first item that is not less than target.
auto it = std::ranges::lower_bound(items, target);
if (it == items.end() || *it != target) {
return -1;
}
return static_cast<long>(it - items.begin());
}
index_of.hpp 9 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/search-a-sorted-list/.
#pragma once
#include <span>
// index_of returns the first index of target in the sorted span items, or -1.
long index_of(std::span<const int> items, int target);
test_index_of.cpp 39 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/search-a-sorted-list/.
#include "index_of.hpp"
#include <iostream>
#include <string_view>
#include <vector>
static int failures = 0;
static void check(std::string_view name, const std::vector<int> &items, int target, long want) {
if (index_of(items, target) != want) {
std::cerr << "case " << name << " failed\n";
failures++;
}
}
int main() {
check("middle", std::vector<int>{1, 3, 5, 7, 9}, 5, 2);
check("first", std::vector<int>{1, 3, 5, 7, 9}, 1, 0);
check("last", std::vector<int>{1, 3, 5, 7, 9}, 9, 4);
check("missing", std::vector<int>{1, 3, 5, 7, 9}, 4, -1);
check("below", std::vector<int>{1, 3, 5}, 0, -1);
check("above", std::vector<int>{1, 3, 5}, 6, -1);
check("empty", std::vector<int>{}, 1, -1);
check("single-hit", std::vector<int>{7}, 7, 0);
check("single-miss", std::vector<int>{7}, 8, -1);
check("duplicates", std::vector<int>{1, 2, 2, 2, 3}, 2, 1);
check("all-same", std::vector<int>{4, 4, 4, 4}, 4, 0);
check("negative", std::vector<int>{-9, -5, -1, 0}, -5, 1);
check("extremes", std::vector<int>{(-2147483647 - 1), 0, 2147483647}, 2147483647, 2);
check("min-target", std::vector<int>{(-2147483647 - 1), 0, 2147483647}, (-2147483647 - 1), 0);
if (failures > 0) {
return 1;
}
std::cout << "all cases pass\n";
return 0;
}
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/search-a-sorted-list/.
final class IndexOf {
private IndexOf() {}
/** Returns the first index of target in the sorted array items, or -1. */
static int indexOf(int[] items, int target) {
// Arrays.binarySearch can return any index of equal items, so this is a
// search for the first index lo with items[lo] >= target.
int lo = 0;
int hi = items.length;
while (lo < hi) {
int mid = lo + (hi - lo) / 2;
if (items[mid] < target) {
lo = mid + 1;
} else {
hi = mid;
}
}
return lo < items.length && items[lo] == target ? lo : -1;
}
}
IndexOfTest.java 35 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/search-a-sorted-list/.
import static org.junit.jupiter.api.Assertions.assertEquals;
import java.util.stream.Stream;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.Arguments;
import org.junit.jupiter.params.provider.MethodSource;
class IndexOfTest {
static Stream<Arguments> cases() {
return Stream.of(
Arguments.of("middle", new int[] {1, 3, 5, 7, 9}, 5, 2),
Arguments.of("first", new int[] {1, 3, 5, 7, 9}, 1, 0),
Arguments.of("last", new int[] {1, 3, 5, 7, 9}, 9, 4),
Arguments.of("missing", new int[] {1, 3, 5, 7, 9}, 4, -1),
Arguments.of("below", new int[] {1, 3, 5}, 0, -1),
Arguments.of("above", new int[] {1, 3, 5}, 6, -1),
Arguments.of("empty", new int[] {}, 1, -1),
Arguments.of("single-hit", new int[] {7}, 7, 0),
Arguments.of("single-miss", new int[] {7}, 8, -1),
Arguments.of("duplicates", new int[] {1, 2, 2, 2, 3}, 2, 1),
Arguments.of("all-same", new int[] {4, 4, 4, 4}, 4, 0),
Arguments.of("negative", new int[] {-9, -5, -1, 0}, -5, 1),
Arguments.of("extremes", new int[] {Integer.MIN_VALUE, 0, 2147483647}, 2147483647, 2),
Arguments.of("min-target", new int[] {Integer.MIN_VALUE, 0, 2147483647}, Integer.MIN_VALUE, 0));
}
@ParameterizedTest(name = "{0}")
@MethodSource("cases")
void indexOf(String name, int[] items, int target, int want) {
assertEquals(want, IndexOf.indexOf(items, target));
}
}
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/search-a-sorted-list/.
#include "index_of.h"
long index_of(const int *items, size_t n, int target) {
// bsearch can return any of the equal items, so this is a search for the
// first index lo with items[lo] >= target.
size_t lo = 0;
size_t hi = n;
while (lo < hi) {
size_t mid = lo + (hi - lo) / 2;
if (items[mid] < target) {
lo = mid + 1;
} else {
hi = mid;
}
}
return lo < n && items[lo] == target ? (long)lo : -1;
}
index_of.h 13 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/search-a-sorted-list/.
#ifndef INDEX_OF_H
#define INDEX_OF_H
#include <stddef.h>
// index_of returns the first index of target in the sorted array
// items[0..n), or -1.
long index_of(const int *items, size_t n, int target);
#endif
test_index_of.c 44 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/search-a-sorted-list/.
#include "index_of.h"
#include <stdio.h>
static int failures = 0;
#define L(...) {__VA_ARGS__}
// An empty list has a 0 in it, because C has no empty array. The count n
// gives the real length.
#define CHECK(name, n, given, target, want) \
do { \
const int g[] = given; \
long got = index_of(g, n, target); \
if (got != (want)) { \
fprintf(stderr, "case %s: got %ld, want %d\n", name, got, want); \
failures++; \
} \
} while (0)
int main(void) {
CHECK("middle", 5, L(1, 3, 5, 7, 9), 5, 2);
CHECK("first", 5, L(1, 3, 5, 7, 9), 1, 0);
CHECK("last", 5, L(1, 3, 5, 7, 9), 9, 4);
CHECK("missing", 5, L(1, 3, 5, 7, 9), 4, -1);
CHECK("below", 3, L(1, 3, 5), 0, -1);
CHECK("above", 3, L(1, 3, 5), 6, -1);
CHECK("empty", 0, L(0), 1, -1);
CHECK("single-hit", 1, L(7), 7, 0);
CHECK("single-miss", 1, L(7), 8, -1);
CHECK("duplicates", 5, L(1, 2, 2, 2, 3), 2, 1);
CHECK("all-same", 4, L(4, 4, 4, 4), 4, 0);
CHECK("negative", 4, L(-9, -5, -1, 0), -5, 1);
CHECK("extremes", 3, L((-2147483647 - 1), 0, 2147483647), 2147483647, 2);
CHECK("min-target", 3, L((-2147483647 - 1), 0, 2147483647), (-2147483647 - 1), 0);
if (failures > 0) {
return 1;
}
printf("all cases pass\n");
return 0;
}
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/search-a-sorted-list/.
public static class IndexOf
{
// Find returns the first index of target in the sorted array items, or -1.
public static int Find(int[] items, int target)
{
// Array.BinarySearch can return any index of equal items, so this is
// a search for the first index lo with items[lo] >= target.
int lo = 0;
int hi = items.Length;
while (lo < hi)
{
int mid = lo + (hi - lo) / 2;
if (items[mid] < target)
{
lo = mid + 1;
}
else
{
hi = mid;
}
}
return lo < items.Length && items[lo] == target ? lo : -1;
}
}
IndexOfTests.cs 33 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/search-a-sorted-list/.
using Xunit;
public sealed class IndexOfTests
{
public static TheoryData<string, int[], int, int> Cases => new()
{
{ "middle", new int[] { 1, 3, 5, 7, 9 }, 5, 2 },
{ "first", new int[] { 1, 3, 5, 7, 9 }, 1, 0 },
{ "last", new int[] { 1, 3, 5, 7, 9 }, 9, 4 },
{ "missing", new int[] { 1, 3, 5, 7, 9 }, 4, -1 },
{ "below", new int[] { 1, 3, 5 }, 0, -1 },
{ "above", new int[] { 1, 3, 5 }, 6, -1 },
{ "empty", new int[0], 1, -1 },
{ "single-hit", new int[] { 7 }, 7, 0 },
{ "single-miss", new int[] { 7 }, 8, -1 },
{ "duplicates", new int[] { 1, 2, 2, 2, 3 }, 2, 1 },
{ "all-same", new int[] { 4, 4, 4, 4 }, 4, 0 },
{ "negative", new int[] { -9, -5, -1, 0 }, -5, 1 },
{ "extremes", new int[] { int.MinValue, 0, 2147483647 }, 2147483647, 2 },
{ "min-target", new int[] { int.MinValue, 0, 2147483647 }, int.MinValue, 0 },
};
[Theory]
[MemberData(nameof(Cases))]
public void Check(string name, int[] items, int target, int want)
{
Assert.NotNull(name);
Assert.Equal(want, IndexOf.Find(items, target));
}
}
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/search-a-sorted-list/.
/**
* @param {number[]} items
* @param {number} target
* @returns {number}
*/
export function indexOf(items, target) {
// Find the first index lo with items[lo] >= target. The search keeps
// items[i] < target for each i < lo, and items[i] >= target for each i >= hi.
let lo = 0;
let hi = items.length;
while (lo < hi) {
const mid = lo + Math.floor((hi - lo) / 2);
if (items[mid] < target) {
lo = mid + 1;
} else {
hi = mid;
}
}
return lo < items.length && items[lo] === target ? lo : -1;
}
index_of.test.js 30 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/search-a-sorted-list/.
import assert from "node:assert/strict";
import { test } from "node:test";
import { indexOf } from "./index_of.js";
const cases = [
["middle", [1, 3, 5, 7, 9], 5, 2],
["first", [1, 3, 5, 7, 9], 1, 0],
["last", [1, 3, 5, 7, 9], 9, 4],
["missing", [1, 3, 5, 7, 9], 4, -1],
["below", [1, 3, 5], 0, -1],
["above", [1, 3, 5], 6, -1],
["empty", [], 1, -1],
["single-hit", [7], 7, 0],
["single-miss", [7], 8, -1],
["duplicates", [1, 2, 2, 2, 3], 2, 1],
["all-same", [4, 4, 4, 4], 4, 0],
["negative", [-9, -5, -1, 0], -5, 1],
["extremes", [-2147483648, 0, 2147483647], 2147483647, 2],
["min-target", [-2147483648, 0, 2147483647], -2147483648, 0],
];
for (const [name, items, target, want] of cases) {
test(name, () => {
assert.equal(indexOf(items, target), want);
});
}
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/search-a-sorted-list/.
export function indexOf(items: readonly number[], target: number): number {
// Find the first index lo with items[lo] >= target. The search keeps
// items[i] < target for each i < lo, and items[i] >= target for each i >= hi.
let lo = 0;
let hi = items.length;
while (lo < hi) {
const mid = lo + Math.floor((hi - lo) / 2);
if (items[mid] < target) {
lo = mid + 1;
} else {
hi = mid;
}
}
return lo < items.length && items[lo] === target ? lo : -1;
}
index_of.test.ts 30 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/search-a-sorted-list/.
import assert from "node:assert/strict";
import { test } from "node:test";
import { indexOf } from "./index_of.ts";
const cases: [string, number[], number, number][] = [
["middle", [1, 3, 5, 7, 9], 5, 2],
["first", [1, 3, 5, 7, 9], 1, 0],
["last", [1, 3, 5, 7, 9], 9, 4],
["missing", [1, 3, 5, 7, 9], 4, -1],
["below", [1, 3, 5], 0, -1],
["above", [1, 3, 5], 6, -1],
["empty", [], 1, -1],
["single-hit", [7], 7, 0],
["single-miss", [7], 8, -1],
["duplicates", [1, 2, 2, 2, 3], 2, 1],
["all-same", [4, 4, 4, 4], 4, 0],
["negative", [-9, -5, -1, 0], -5, 1],
["extremes", [-2147483648, 0, 2147483647], 2147483647, 2],
["min-target", [-2147483648, 0, 2147483647], -2147483648, 0],
];
for (const [name, items, target, want] of cases) {
test(name, () => {
assert.equal(indexOf(items, target), want);
});
}
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/search-a-sorted-list/.
// Package indexof searches a sorted slice.
package indexof
import "slices"
// IndexOf returns the first index of target in the sorted slice items, or -1.
func IndexOf(items []int, target int) int {
// BinarySearch gives the earliest position, and found tells if the item
// at that position is equal to target.
i, found := slices.BinarySearch(items, target)
if !found {
return -1
}
return i
}
index_of_test.go 36 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/search-a-sorted-list/.
package indexof
import "testing"
var cases = []struct {
name string
items []int
target int
want int
}{
{"middle", []int{1, 3, 5, 7, 9}, 5, 2},
{"first", []int{1, 3, 5, 7, 9}, 1, 0},
{"last", []int{1, 3, 5, 7, 9}, 9, 4},
{"missing", []int{1, 3, 5, 7, 9}, 4, -1},
{"below", []int{1, 3, 5}, 0, -1},
{"above", []int{1, 3, 5}, 6, -1},
{"empty", []int{}, 1, -1},
{"single-hit", []int{7}, 7, 0},
{"single-miss", []int{7}, 8, -1},
{"duplicates", []int{1, 2, 2, 2, 3}, 2, 1},
{"all-same", []int{4, 4, 4, 4}, 4, 0},
{"negative", []int{-9, -5, -1, 0}, -5, 1},
{"extremes", []int{-2147483648, 0, 2147483647}, 2147483647, 2},
{"min-target", []int{-2147483648, 0, 2147483647}, -2147483648, 0},
}
func TestIndexOf(t *testing.T) {
for _, c := range cases {
if got := IndexOf(c.items, c.target); got != c.want {
t.Errorf("%s: got %d, want %d", c.name, got, c.want)
}
}
}
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/search-a-sorted-list/.
/// Returns the first index of `target` in the sorted slice `items`, or -1.
pub fn index_of(items: &[i32], target: i32) -> i64 {
// binary_search can return any index of equal items. partition_point
// gives the first index i with items[i] >= target.
let i = items.partition_point(|&x| x < target);
if i < items.len() && items[i] == target {
i64::try_from(i).expect("index_of: the index does not fit in an i64")
} else {
-1
}
}
tests/index_of_test.rs 27 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/search-a-sorted-list/.
use algo_search_a_sorted_list::index_of;
#[test]
fn cases() {
let cases: &[(&str, &[i32], i32, i64)] = &[
("middle", &[1, 3, 5, 7, 9], 5, 2),
("first", &[1, 3, 5, 7, 9], 1, 0),
("last", &[1, 3, 5, 7, 9], 9, 4),
("missing", &[1, 3, 5, 7, 9], 4, -1),
("below", &[1, 3, 5], 0, -1),
("above", &[1, 3, 5], 6, -1),
("empty", &[], 1, -1),
("single-hit", &[7], 7, 0),
("single-miss", &[7], 8, -1),
("duplicates", &[1, 2, 2, 2, 3], 2, 1),
("all-same", &[4, 4, 4, 4], 4, 0),
("negative", &[-9, -5, -1, 0], -5, 1),
("extremes", &[-2147483648, 0, 2147483647], 2147483647, 2),
("min-target", &[-2147483648, 0, 2147483647], -2147483648, 0),
];
for &(name, items, target, want) in cases {
assert_eq!(index_of(items, target), want, "{name}");
}
}
#!/usr/bin/env bash
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/search-a-sorted-list/.
# index_of TARGET ITEM...
# Prints the first index of TARGET in the sorted integer items, or -1.
index_of() {
local target=$1
shift
local -a items=("$@")
local lo=0 hi=${#items[@]} mid
while ((lo < hi)); do
mid=$((lo + (hi - lo) / 2))
# (( )) compares numbers. [[ a < b ]] would compare text.
if ((items[mid] < target)); then
lo=$((mid + 1))
else
hi=$mid
fi
done
if ((lo < ${#items[@]})) && ((items[lo] == target)); then
printf '%s\n' "$lo"
else
printf '%s\n' -1
fi
}
test_index_of.bats 34 lines
#!/usr/bin/env bats
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/search-a-sorted-list/.
bats_require_minimum_version 1.5.0
setup() {
source "$BATS_TEST_DIRNAME/index_of.sh"
}
check() { # check FUNCTION GIVEN... -- WANT
local fn=$1 got
shift
local -a given=()
while [ "$1" != -- ]; do given+=("$1"); shift; done
shift
got=$("$fn" "${given[@]}")
[ "$got" = "$1" ] || { printf 'got: %s\nwant: %s\n' "$got" "$1"; return 1; }
}
@test "middle" { check index_of 5 1 3 5 7 9 -- 2; }
@test "first" { check index_of 1 1 3 5 7 9 -- 0; }
@test "last" { check index_of 9 1 3 5 7 9 -- 4; }
@test "missing" { check index_of 4 1 3 5 7 9 -- -1; }
@test "below" { check index_of 0 1 3 5 -- -1; }
@test "above" { check index_of 6 1 3 5 -- -1; }
@test "empty" { check index_of 1 -- -1; }
@test "single-hit" { check index_of 7 7 -- 0; }
@test "single-miss" { check index_of 8 7 -- -1; }
@test "duplicates" { check index_of 2 1 2 2 2 3 -- 1; }
@test "all-same" { check index_of 4 4 4 4 4 -- 0; }
@test "negative" { check index_of -5 -9 -5 -1 0 -- 1; }
@test "extremes" { check index_of 2147483647 -2147483648 0 2147483647 -- 2; }
@test "min-target" { check index_of -2147483648 -2147483648 0 2147483647 -- 0; }
References
- The Python Standard Library, bisect, bisect.bisect_left()
- Java SE 25 API, Class Arrays, binarySearch(int[], int)
- Go standard library, package slices, BinarySearch
- cppreference.com, bsearch, bsearch_s, Description
- MDN Web Docs, Array.prototype.indexOf(), Description
- .NET API reference, Array.BinarySearch method, Returns
- Rust standard library, primitive type slice, binary_search, partition_point
- cppreference.com, std::binary_search, Return value
- Bash Reference Manual, 3.2.5.2 Conditional Constructs, [[...]]
About this page
The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H0 no proof |
|
| Lean | L0 no Lean part |
|
| Code (bash) | I0 not checked yet |
|
| Code (c) | I0 not checked yet |
|
| Code (cpp) | I0 not checked yet |
|
| Code (csharp) | I0 not checked yet |
|
| Code (go) | I0 not checked yet |
|
| Code (java) | I0 not checked yet |
|
| Code (javascript) | I0 not checked yet |
|
| Code (python) | I0 not checked yet |
|
| Code (rust) | I0 not checked yet |
|
| Code (typescript) | I0 not checked yet |
|
| Visual | V0 none |
|
| Writing | W3 standard |
|
Tag T5W8S8 Edit this page History Report an error Markdown