1. Binary search in sorted collections
Binary search, also known as binary chop or logarithmic search, is a deterministic algorithm for ordered data structures. It maintains a search interval defined by lower and upper indices. Each comparison at the midpoint eliminates approximately half of the remaining candidates. A conventional exact-match search can stop when it finds a match; a boundary search continues until it locates the required boundary.
Ordering is a precondition. Sorting once before repeated searches can be worthwhile, but the cost of preparing and validating the data must be included when assessing overall performance. Hash-based lookup can provide expected constant-time exact matches; binary search is particularly useful when order matters, for example for insertion positions, rank, predecessor, successor and range queries.
The SEARCH package in APPSDEMO provides reusable numeric search functions. This article examines the rightmost-match implementation and the care needed when duplicate values occur.
GitHub - SEARCH package specification · package body
2. The SEARCH package
The package provides 19 public functions: nine pairs of list and array interfaces, plus the original BINARY_CHOP_SEARCH. The list wrappers convert comma-separated values to a numeric VARRAY. Use the array interfaces when the data is already in a collection.
| List function | Array function | Arguments | Purpose |
|---|---|---|---|
binary_chop_search | — | p_key, p_list | Sort the list, then find any exact match in the sorted array. |
binary_search | binary_search_array | p_target, collection | Find any exact match. |
binary_rank | binary_rank_array | p_target, collection | Count values strictly smaller than the target. |
binary_search_leftmost | binary_search_leftmost_array | p_target, collection, p_exact_match | First match, or missing-value insertion position in non-exact mode. |
binary_search_rightmost | binary_search_rightmost_array | p_target, collection, p_exact_match | Last match, or missing-value insertion position in non-exact mode. |
binary_search_predecessor | binary_search_predecessor_array | p_target, collection | Last position strictly below target. |
binary_search_successor | binary_search_successor_array | p_target, collection | First position strictly above target. |
binary_search_nearest | binary_search_nearest_array | p_target, collection | Nearest strict predecessor or successor; ties choose the higher value. |
binary_search_range | binary_search_range_array | p_range_from, p_range_to, collection | Inclusive count, including duplicates; reversed range returns 0. |
search_unsorted | search_unsorted_array | p_target, collection | Linear search for first match; ignores NULL elements. |
The collection argument is p_list (a comma-separated string) or p_array (a PLSQL_TYPES.T_NUMBER_ARRAY VARRAY). Binary search functions require ascending order and no NULL elements, except BINARY_CHOP_SEARCH which sorts its input. SEARCH_UNSORTED is a separate linear search. Positions are one-based. The return value 0 denotes no match, no neighbour or a zero count; NULL denotes an invalid input or error. An initialised empty array is valid, but an uninitialised array and a NULL or empty list string are invalid. Targets, range limits and the Boolean exact-match flag must not be NULL.
For leftmost and rightmost searches the flag defaults to TRUE. If the flag is FALSE and the target exists, the function still returns its first or last matching position. Only an absent target returns its insertion position, which may be COUNT + 1 (append), or 1 for an empty array. This convention is not an unconditional upper-bound operation.
3. Why the rightmost match is different
Consider this sorted array of 13 elements, with positions starting at 1:
1,1,2,2,2,3,4,4,4,4,5,6,8
A conventional search for 4 could return any of positions 7 through 10. A leftmost search should return position 7 and a rightmost search should return position 10. The values alone are not enough; the position is part of the result.
In a sorted array the matching values form one contiguous run. A useful way to describe its boundaries is the lower bound (first value greater than or equal to the target) and upper bound (first value strictly greater than the target). If no such element exists, the conventional bound is one past the end of the array. A rightmost exact match is the upper bound minus one, provided that position contains the target.
4. Implementing BINARY_SEARCH_RIGHTMOST_ARRAY in PL/SQL
The following excerpts are from the package body. The VARRAY is one-based and dense. Validation checks the input before the search begins; COUNT also works for an initialised empty array. The complete exception handling is in the linked package source.
Core algorithm
FUNCTION binary_search_rightmost_array(
p_target IN NUMBER,
p_array IN plsql_types.t_number_array,
p_exact_match IN BOOLEAN DEFAULT TRUE
) RETURN NUMBER
IS
l PLS_INTEGER; -- Left bound of array to search
r PLS_INTEGER; -- Right bound of array to search
n PLS_INTEGER; -- Number of array elements
t NUMBER; -- Search target value
m PLS_INTEGER; -- Mid position of range [l,r]
p PLS_INTEGER; -- Position of target
v_debug_module applog.program_name%TYPE := 'SEARCH.BINARY_SEARCH_RIGHTMOST_ARRAY';
v_debug_msg applog.message%TYPE;
v_debug_mode VARCHAR2(1) := 'X';
e_null_value EXCEPTION;
e_unsorted_array EXCEPTION;
BEGIN
IF p_target IS NULL OR p_exact_match IS NULL THEN
RAISE e_invalid_data;
END IF;
IF util_numeric.array_contains_null(p_array) THEN
RAISE e_null_value;
END IF;
IF NOT util_numeric.is_sorted_array(p_array) THEN
RAISE e_unsorted_array;
END IF;
t := p_target;
n := p_array.COUNT;
l := 1;
r := n + 1; -- One-past-end boundary; never dereferenced.
p := 0;
-- Find first position whose value is > target, or n + 1.
WHILE l < r LOOP
m := l + floor((r -l) / 2);
v_debug_msg := 'In WHILE loop. m=' || to_char(m) || ' l=' || to_char(l) || ' r=' || to_char(r);
util_admin.log_message(v_debug_msg, sqlerrm, v_debug_module, v_debug_mode, gc_info);
IF p_array(m) > t THEN
util_admin.log_message('p_array(m) > t THEN r:=m; m=' || to_char(m), sqlerrm, v_debug_module, v_debug_mode, gc_info);
r := m;
ELSE
util_admin.log_message('ELSE l := m+1 =' || to_char(m+1), sqlerrm, v_debug_module, v_debug_mode, gc_info);
l := m+1;
END IF;
END LOOP;
The inclusive interval of possible boundary positions is [1, n + 1]. The boundary is the first index whose value is strictly greater than the target; when no greater value exists it is n + 1. This sentinel is a position, not an actual array element. Because l is strictly less than r whenever the midpoint is evaluated, m never exceeds n.
If the midpoint value is greater than the target, the boundary lies at or before m, so r becomes m. Otherwise, it lies after m, so l becomes m + 1. This preserves the boundary invariant and strictly shrinks the interval until l = r. An empty array starts with l = r = 1 and no array element is accessed.
Worked search for 4
| Iteration | l | r | m | Value at m | Next interval |
|---|---|---|---|---|---|
| 1 | 1 | 14 | 7 | 4 | [8, 14] |
| 2 | 8 | 14 | 11 | 5 | [8, 11] |
| 3 | 8 | 11 | 9 | 4 | [10, 11] |
| 4 | 10 | 11 | 10 | 4 | [11, 11] |
At termination the first greater value is at position 11. Position 10 contains 4, so the function returns 10.
Resolution logic
IF l > 1 AND p_array(l-1) = t THEN
p := l - 1; -- Rightmost matching value, including the last element.
ELSIF p_exact_match THEN
p := 0; -- No exact match.
ELSE
p := l; -- Insertion position, including n + 1.
END IF;
RETURN p;
PL/SQL short-circuit evaluation protects the array access when l = 1. A match at the final element is handled naturally by l = n + 1. An absent target above the maximum returns n + 1 in non-exact mode, or 0 in exact mode.
5. Derived searches and boundary testing
The lower boundary is the first value greater than or equal to a target. The leftmost non-exact search returns this position; subtracting one gives the rank and the predecessor position. The successor routine converts the rightmost non-exact result into the first strictly greater position (or 0 when there is none). The nearest function compares those two strict neighbours and chooses the successor if the distances are equal. A match to the target itself is excluded.
For an inclusive range, the count is the upper boundary minus the lower boundary. The successor function uses 0 for no successor, so substitute COUNT + 1 in this calculation. This counts duplicates correctly and does not require either limit to be present.
FUNCTION binary_search_range_array(
p_range_from IN NUMBER,
p_range_to IN NUMBER,
p_array IN plsql_types.t_number_array
) RETURN NUMBER
IS
v_lower_bound NUMBER;
v_upper_bound NUMBER;
BEGIN
-- Inclusive range: first value >= lower limit, first value > upper limit.
v_lower_bound := search.binary_search_leftmost_array(p_range_from, p_array, FALSE);
v_upper_bound := search.binary_search_successor_array(p_range_to, p_array);
IF v_lower_bound IS NULL OR v_upper_bound IS NULL THEN
RETURN NULL;
END IF;
IF p_range_from > p_range_to THEN
RETURN 0; -- Empty range.
END IF;
IF v_upper_bound = 0 THEN
v_upper_bound := p_array.COUNT + 1;
END IF;
RETURN v_upper_bound - v_lower_bound;
EXCEPTION
WHEN OTHERS THEN
util_admin.log_message('Unexpected error.', sqlerrm, 'SEARCH.BINARY_SEARCH_RANGE_ARRAY', 'S', gc_error);
RETURN NULL;
END binary_search_range_array;
For the sample array, the range 4 to 4 has lower boundary 7 and upper boundary 11, giving 11 - 7 = 4 values. The range 4 to 4.5 also contains four values, and 9 to 99 contains none.
| Target | Exact match | Non-exact | Reason |
|---|---|---|---|
| 0 | 0 | 1 | Before first value |
| 1 | 2 | 2 | Duplicates at start |
| 4 | 10 | 10 | Four matching values |
| 7 | 0 | 13 | Missing value before 8 |
| 8 | 13 | 13 | Match at last element |
| 9 | 0 | 14 | Append after last value |
Also test initialised empty and uninitialised arrays, single elements, arrays with all values equal, missing neighbours, fractional numbers, reversed ranges, invalid lists, unsorted inputs and NULL values. Invalid inputs return NULL and report diagnostics. A valid empty array returns 0 for matches, neighbours, rank and range count, or 1 for non-exact insertion positions.
6. Complexity and the cost of validation
The binary search loop requires O(log n) comparisons and O(1) auxiliary space, excluding the input collection. For a non-empty array of 32,767 elements, the boundary loop requires at most 15 iterations. The final resolution adds a constant number of comparisons. The figure 32,767 is an example collection size, not a universal Oracle VARRAY size limit.
The complete function also calls UTIL_NUMERIC.ARRAY_CONTAINS_NULL and UTIL_NUMERIC.IS_SORTED_ARRAY. Checking all elements for NULLs and verifying ascending order by scanning the array takes O(n) time. If these checks are performed on every call, they can dominate the logarithmic search. The list-based interface must also account for parsing and collection construction. Derived searches may perform more than one validation and boundary search. The original binary chop function sorts the list using a quadratic sort, and SEARCH_UNSORTED performs a linear scan. Diagnostic logging calls may also add overhead.
For repeated searches, consider validating the collection once at an appropriate boundary and then searching the unchanged, validated data. This is an architectural trade-off between defensive validation, reuse and performance; it is not a claim that the supplied package already implements such an optimisation.
7. Why not just use SQL?
If the source data is already stored in relational tables, SQL is usually the appropriate tool for filtering, ranking and aggregation. Oracle's optimizer, indexes and analytic functions can avoid unnecessary procedural data processing. For example, the following query returns the largest row number assigned to a given salary in the SCOTT EMP table.
SELECT MAX(pos)
FROM (
SELECT sal,
ROW_NUMBER() OVER (ORDER BY sal) AS pos
FROM emp
)
WHERE sal = :target;
Duplicate salaries form a contiguous group in salary order. MAX(pos) returns the last position in that group, or NULL if the salary is absent (rather than the PL/SQL routine's exact-match sentinel of 0). If the identity of a particular employee among equal salaries matters, include a unique tie-breaker such as EMPNO in the analytic ORDER BY.
The SEARCH package addresses a different problem: algorithms operating on existing in-memory collections, independent of a particular table structure. Examples include finding boundaries in sorted samples, locating a neighbour and counting or ranking values. A validated collection can be searched without repeatedly querying a database table, but the choice between SQL and PL/SQL should be driven by the location of the data, the semantics required and measured performance.
8. Next steps
In Blog 11 - Statistics Library, we use reusable numeric routines to analyse data, including frequency distributions.
