ℹ️ Select 'Choose Exercise', or randomize 'Next Random Exercise' in selected language.

Choose Exercise:
Timer 00:00
WPM --
Score --
Acc --
Correct chars --

SQL ANSI: Implement Binary Search on a Sorted Array

SQL ANSI

Goal -- WPM

Ready
Exercise Algorithm Area
1CREATE OR REPLACE FUNCTION binary_search_in_array(
2p_array_table_name TEXT,
3p_value_column TEXT,
4p_index_column TEXT,
5p_target_value ANYELEMENT,
6p_array_size INT
7) RETURNS INT AS $$
8DECLARE
9v_low INT := 0;
10v_high INT;
11v_mid INT;
12v_current_value ANYELEMENT;
13v_query TEXT;
14v_found_index INT := -1; -- Default to -1 if not found
15BEGIN
16-- Basic validation: Check if array size is valid
17IF p_array_size <= 0 THEN
18RETURN -1; -- Array is empty or invalid size
19END IF;
20
21v_high := p_array_size - 1;
22
23-- Construct the dynamic SQL query to fetch values based on index
24-- This is a simplified approach; a real-world scenario might involve a temporary table or more robust dynamic SQL.
25-- For demonstration, we assume a structure where we can query by index.
26
27WHILE v_low <= v_high LOOP
28v_mid := v_low + FLOOR((v_high - v_low) / 2);
29
30-- Dynamically construct and execute query to get the value at v_mid index
31v_query := format('SELECT %I FROM %I WHERE %I = %L ORDER BY %I LIMIT 1',
32p_value_column, p_array_table_name, p_index_column, v_mid, p_index_column);
33BEGIN
34EXECUTE v_query INTO v_current_value;
35EXCEPTION WHEN NO_DATA_FOUND THEN
36-- This should ideally not happen if p_array_size is correct and array is contiguous
37-- but as a safeguard.
38RETURN -1;
39END;
40
41-- Compare the target value with the current value
42IF v_current_value = p_target_value THEN
43v_found_index := v_mid;
44EXIT; -- Target found, exit loop
45ELSIF v_current_value < p_target_value THEN
46-- Target is in the right half
47v_low := v_mid + 1;
48ELSE
49-- Target is in the left half
50v_high := v_mid - 1;
51END IF;
52END LOOP;
53
54-- If the loop finishes and v_found_index is still -1, the element was not found.
55-- However, the loop condition v_low <= v_high ensures we cover all possibilities.
56-- If v_found_index is not -1, it holds the index where the element was found.
57RETURN v_found_index;
58END;
59$$ LANGUAGE plpgsql;
60
61-- Helper function to get array size (example)
62CREATE OR REPLACE FUNCTION get_array_size(
63p_array_table_name TEXT,
64p_index_column TEXT
65) RETURNS INT AS $$
66DECLARE
67v_size INT;
68v_query TEXT;
69BEGIN
70v_query := format('SELECT COUNT(*) FROM %I', p_array_table_name);
71EXECUTE v_query INTO v_size;
72RETURN v_size;
73END;
74$$ LANGUAGE plpgsql;
75
76-- Example Usage:
77-- Assuming a table named 'sorted_numbers' with columns 'idx' (integer) and 'val' (integer)
78-- INSERT INTO sorted_numbers (idx, val) VALUES (0, 2), (1, 5), (2, 8), (3, 12), (4, 16), (5, 23), (6, 38), (7, 56), (8, 72), (9, 91);
79-- SELECT binary_search_in_array('sorted_numbers', 'val', 'idx', 23, get_array_size('sorted_numbers', 'idx')); -- Should return 5
80-- SELECT binary_search_in_array('sorted_numbers', 'val', 'idx', 10, get_array_size('sorted_numbers', 'idx')); -- Should return -1
81-- SELECT binary_search_in_array('sorted_numbers', 'val', 'idx', 2, get_array_size('sorted_numbers', 'idx')); -- Should return 0
82-- SELECT binary_search_in_array('sorted_numbers', 'val', 'idx', 91, get_array_size('sorted_numbers', 'idx')); -- Should return 9
83-- SELECT binary_search_in_array('sorted_numbers', 'val', 'idx', 1, get_array_size('sorted_numbers', 'idx')); -- Should return -1 (less than min)
84-- SELECT binary_search_in_array('sorted_numbers', 'val', 'idx', 100, get_array_size('sorted_numbers', 'idx')); -- Should return -1 (greater than max)
Algorithm description viewbox

SQL ANSI: Implement Binary Search on a Sorted Array

Algorithm description:

This SQL function implements the binary search algorithm to find the index of a target value within a sorted array represented by a database table. It efficiently narrows down the search space by repeatedly dividing the array in half. This is crucial for optimizing search operations on large, ordered datasets where linear scans would be too slow.

Algorithm explanation:

The `binary_search_in_array` function takes the table name, value column, index column, target value, and array size as input. It initializes `v_low` to 0 and `v_high` to `p_array_size - 1`. The core of the algorithm is a `WHILE` loop that continues as long as `v_low <= v_high`. In each iteration, it calculates the middle index `v_mid`. Dynamic SQL is used to fetch the value at `v_mid` from the specified table and column. If the `v_current_value` matches `p_target_value`, the index `v_mid` is returned. If `v_current_value` is less than `p_target_value`, `v_low` is updated to `v_mid + 1`; otherwise, `v_high` is updated to `v_mid - 1`. If the loop completes without finding the target, -1 is returned. The time complexity is O(log N), where N is the size of the array, due to the halving of the search space in each step. The space complexity is O(1) for variables, plus the overhead of dynamic SQL execution. Edge cases handled include an empty or invalid-sized array, and the target value not being present in the array. The invariant maintained is that the target value, if present, always lies within the range `[v_low, v_high]` inclusive.

Pseudocode:

Function binary_search_in_array(array_table, value_col, index_col, target, array_size):
  IF array_size <= 0 THEN
    RETURN -1
  END IF

  low = 0
  high = array_size - 1

  WHILE low <= high:
    mid = low + floor((high - low) / 2)
    current_value = fetch value from array_table at index_col = mid, from value_col

    IF current_value == target THEN
      RETURN mid
    ELSE IF current_value < target THEN
      low = mid + 1
    ELSE
      high = mid - 1
    END IF
  END WHILE

  RETURN -1 -- Target not found