Giả sử có một bảng sorted_numbers có cột chứa số tự nhiên đã sắp xếp. Ta có thể tạo thủ tục SQL để thực thi thuật toán tìm kiếm nhị phân để tìm một số cụ thể trong bảng như sau:
CREATE OR REPLACE PROCEDURE binary_search(p_search_number NUMBER) AS
v_lower_bound NUMBER := 1;
v_upper_bound NUMBER;
v_mid_point NUMBER;
v_found_number NUMBER;
BEGIN
-- Find the upper bound (maximum) in the table.
SELECT MAX(number_column) INTO v_upper_bound FROM sorted_numbers;
WHILE v_lower_bound <= v_upper_bound LOOP
-- Calculate the midpoint of the range.
v_mid_point := (v_lower_bound + v_upper_bound) / 2;
-- Retrieve the number at the midpoint.
SELECT number_column INTO v_found_number
FROM sorted_numbers
WHERE rownum = v_mid_point;
IF v_found_number = p_search_number THEN
DBMS_OUTPUT.PUT_LINE('Number ' || p_search_number || ' is found.');
RETURN; -- Exit the procedure when the number is found.
ELSIF v_found_number < p_search_number THEN
-- If the number at the midpoint is less than the search number,
-- narrow the search range to the upper half.
v_lower_bound := v_mid_point + 1;
ELSE
-- If the number at the midpoint is greater than the search number,
-- narrow the search range to the lower half.
v_upper_bound := v_mid_point - 1;
END IF;
END LOOP;
DBMS_OUTPUT.PUT_LINE('Number ' || p_search_number || ' is not found.');
END;
Để thực thi procedure, ta có thể sử dụng lệnh sau:
SET SERVEROUTPUT ON; -- Enable DBMS_OUTPUT for displaying results.
BEGIN
binary_search(42); -- Call the procedure with the desired number.
END;