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

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

T-SQL: Implement Binary Search

T-SQL

Goal -- WPM

Ready
Exercise Algorithm Area
1CREATE FUNCTION dbo.BinarySearch (@SortedArray NVARCHAR(MAX), @Target INT)
2RETURNS INT
3AS
4BEGIN
5-- Representing the array as a delimited string for simplicity in T-SQL
6-- In a real scenario, a table variable or temp table would be better.
7-- Example: '1,2,3,4,5,6,7,8,9,10'
8
9DECLARE @Array TABLE (Value INT, Index INT IDENTITY(0,1));
10DECLARE @CurrentPos INT = 1;
11DECLARE @DelimiterPos INT;
12DECLARE @CurrentValueStr NVARCHAR(MAX);
13DECLARE @CurrentValue INT;
14
15-- Populate the table variable from the delimited string
16WHILE @CurrentPos <= LEN(@SortedArray)
17BEGIN
18SET @DelimiterPos = CHARINDEX(',', @SortedArray, @CurrentPos);
19IF @DelimiterPos = 0
20BEGIN
21SET @CurrentValueStr = SUBSTRING(@SortedArray, @CurrentPos, LEN(@SortedArray));
22SET @CurrentPos = LEN(@SortedArray) + 1;
23END
24ELSE
25BEGIN
26SET @CurrentValueStr = SUBSTRING(@SortedArray, @CurrentPos, @DelimiterPos - @CurrentPos);
27SET @CurrentPos = @DelimiterPos + 1;
28END
29
30-- Handle potential non-integer values gracefully
31IF ISNUMERIC(@CurrentValueStr) = 1
32BEGIN
33SET @CurrentValue = CAST(@CurrentValueStr AS INT);
34INSERT INTO @Array (Value) VALUES (@CurrentValue);
35END
36ELSE
37BEGIN
38-- Skip non-numeric entries, or handle as an error if strict validation is needed
39CONTINUE;
40END
41END
42
43DECLARE @Low INT = 0;
44DECLARE @High INT = (SELECT COUNT(*) FROM @Array) - 1;
45DECLARE @Mid INT;
46
47-- Handle empty array case
48IF @High < @Low
49BEGIN
50RETURN -1; -- Target not found in empty array
51END
52
53WHILE @Low <= @High
54BEGIN
55-- Calculate midpoint to avoid potential overflow with (Low + High) / 2
56SET @Mid = @Low + (@High - @Low) / 2;
57
58DECLARE @MidValue INT;
59SELECT @MidValue = Value FROM @Array WHERE Index = @Mid;
60
61IF @MidValue = @Target
62BEGIN
63RETURN @Mid; -- Target found at index @Mid
64END
65ELSE IF @MidValue < @Target
66BEGIN
67SET @Low = @Mid + 1; -- Target is in the right half
68END
69ELSE
70BEGIN
71SET @High = @Mid - 1; -- Target is in the left half
72END
73END
74
75RETURN -1; -- Target not found
76END
Algorithm description viewbox

T-SQL: Implement Binary Search

Algorithm description:

This T-SQL function implements the binary search algorithm to efficiently find the index of a target integer within a sorted array. The array is represented as a comma-separated string, which is then parsed into a table variable for processing. The algorithm repeatedly divides the search interval in half. If the value at the middle index matches the target, its index is returned. Otherwise, the search continues in the lower or upper half depending on whether the middle value is less than or greater than the target. This is crucial for searching large, sorted datasets quickly.

Algorithm explanation:

The function first parses a comma-separated string into a table variable, assigning an index to each element. It initializes `Low` to 0 and `High` to the last index of the array. The core loop continues as long as `Low` is less than or equal to `High`. In each iteration, it calculates the middle index (`Mid`) using a method that prevents integer overflow. It then compares the value at `Mid` with the `Target`. If they match, `Mid` is returned. If the middle value is less than the target, `Low` is updated to `Mid + 1` to search the right half. If the middle value is greater than the target, `High` is updated to `Mid - 1` to search the left half. If the loop finishes without finding the target, -1 is returned. The time complexity is O(log N) due to the halving of the search space in each step. The space complexity is O(N) for storing the array in the table variable, plus O(1) for variables. Edge cases handled include an empty input array, the target being the first or last element, and the target not being present.

Pseudocode:

FUNCTION BinarySearch(sortedArray, target):
  Parse sortedArray into an array structure with indices
  low = 0
  high = length(array) - 1

  IF array is empty THEN RETURN -1

  WHILE low <= high:
    mid = low + (high - low) / 2
    midValue = array[mid]

    IF midValue == target THEN RETURN mid
    ELSE IF midValue < target THEN
      low = mid + 1
    ELSE
      high = mid - 1

  RETURN -1