PL/pgSQL Iterative Binary Search for Element in Sorted Array
CREATE OR REPLACE FUNCTION iterative_binary_search( sorted_array INT[], target_value INT ) RETURNS INT AS $$ DECLARE low INT; high INT; mid INT; BEGIN -- Handle edge case: empty array. IF array_length(sorted_array, 1) IS NULL OR array_length(sorted_array, 1) = 0 THEN RETURN -1; -...
This PL/pgSQL function implements an iterative binary search algorithm to efficiently find the index of a specific target value within a sorted array of integers. Binary search is a fundamental algorithm for searching in...
The `iterative_binary_search` function operates on a sorted array by repeatedly dividing the search interval in half. It initializes `low` and `high` pointers to the boundaries of the array. The `WHILE` loop continues as long as `low` is less than or equal to `high`, ensuring the search interval is valid. In each iteration, the `mid` index is calculated. If the element at `mid` matches the `target_value`, its index is returned. If the `target_value` is greater than `sorted_array[mid]`, the search continues in the right half by setting `low` to `mid + 1`. Conversely, if the `target_value` is smaller, the search continues in the left half by setting `high` to `mid - 1`. This process guarantees that if the target exists, it will be found. The time complexity is O(log n), where n is the number of elements in the array, due to the halving of the search space in each step. The space complexity is O(1) as it only uses a few variables. Edge cases like an empty array or the target not being present are handled by returning -1.
FUNCTION iterative_binary_search(sorted_array, target_value): IF sorted_array is empty THEN RETURN -1 END IF low = 0 (or 1 for 1-indexed arrays) high = length(sorted_array) - 1 (or length for 1-indexed arrays) WHILE low...