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

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

T-SQL: Implement Bubble Sort

T-SQL

Goal -- WPM

Ready
Exercise Algorithm Area
1CREATE FUNCTION dbo.BubbleSort (@NumberList NVARCHAR(MAX))
2RETURNS NVARCHAR(MAX)
3AS
4BEGIN
5DECLARE @Numbers TABLE (Value INT, RowNum INT IDENTITY(1,1));
6DECLARE @i INT = 1;
7DECLARE @Len INT = LEN(@NumberList);
8DECLARE @CurrentNumStr NVARCHAR(MAX);
9DECLARE @DelimiterPos INT;
10
11-- Handle empty input string
12IF @Len = 0 RETURN '';
13
14-- Parse the comma-separated string into a table variable
15WHILE @i <= @Len
16BEGIN
17SET @DelimiterPos = CHARINDEX(',', @NumberList, @i);
18IF @DelimiterPos = 0
19BEGIN
20SET @CurrentNumStr = SUBSTRING(@NumberList, @i, @Len);
21SET @i = @Len + 1;
22END
23ELSE
24BEGIN
25SET @CurrentNumStr = SUBSTRING(@NumberList, @i, @DelimiterPos - @i);
26SET @i = @DelimiterPos + 1;
27END
28
29-- Ensure the parsed value is numeric before casting
30IF ISNUMERIC(@CurrentNumStr) = 1
31BEGIN
32INSERT INTO @Numbers (Value) VALUES (CAST(@CurrentNumStr AS INT));
33END
34ELSE
35BEGIN
36-- Skip non-numeric entries
37CONTINUE;
38END
39END
40
41DECLARE @Count INT = (SELECT COUNT(*) FROM @Numbers);
42
43-- Handle case where no valid numbers were parsed or list is too small to sort
44IF @Count <= 1 RETURN @NumberList;
45
46DECLARE @Swapped BIT = 1;
47DECLARE @OuterLoopCounter INT = 0;
48
49-- Outer loop for passes
50WHILE @Swapped = 1 AND @OuterLoopCounter < @Count - 1
51BEGIN
52SET @Swapped = 0;
53DECLARE @CurrentRow INT = 1;
54DECLARE @NextRow INT;
55DECLARE @CurrentVal INT, @NextVal INT;
56
57-- Inner loop for comparisons and swaps
58WHILE @CurrentRow < @Count - @OuterLoopCounter
59BEGIN
60SET @NextRow = @CurrentRow + 1;
61
62SELECT @CurrentVal = Value FROM @Numbers WHERE RowNum = @CurrentRow;
63SELECT @NextVal = Value FROM @Numbers WHERE RowNum = @NextRow;
64
65IF @CurrentVal > @NextVal
66BEGIN
67-- Swap elements
68UPDATE @Numbers SET Value = @NextVal WHERE RowNum = @CurrentRow;
69UPDATE @Numbers SET Value = @CurrentVal WHERE RowNum = @NextRow;
70SET @Swapped = 1;
71END
72SET @CurrentRow = @CurrentRow + 1;
73END
74SET @OuterLoopCounter = @OuterLoopCounter + 1;
75END
76
77-- Reconstruct the sorted string
78DECLARE @SortedString NVARCHAR(MAX) = '';
79SELECT @SortedString = @SortedString + CAST(Value AS NVARCHAR(MAX)) + ',' FROM @Numbers ORDER BY RowNum;
80
81-- Remove trailing comma
82IF LEN(@SortedString) > 0
83BEGIN
84SET @SortedString = LEFT(@SortedString, LEN(@SortedString) - 1);
85END
86
87RETURN @SortedString;
88END
Algorithm description viewbox

T-SQL: Implement Bubble Sort

Algorithm description:

This T-SQL function implements the Bubble Sort algorithm to sort a list of integers. The input is a comma-separated string, which is parsed into a table. The algorithm then repeatedly steps through the list, compares adjacent elements, and swaps them if they are in the wrong order. Passes continue until no swaps are needed, indicating the list is sorted. The sorted list is then returned as a comma-separated string. This is a fundamental sorting algorithm, good for understanding basic sorting mechanics.

Algorithm explanation:

The function first parses the input string into a table variable, assigning row numbers. It handles empty or single-element lists by returning them as is. The core of Bubble Sort involves nested loops. The outer loop controls the number of passes, and the inner loop iterates through adjacent elements. If adjacent elements are out of order (current > next), they are swapped, and a flag `Swapped` is set. The outer loop continues as long as a swap occurred in the previous pass and the number of passes is less than the total count minus one. The time complexity is O(N^2) in the worst and average cases, where N is the number of elements, due to the nested loops. The space complexity is O(N) for storing the numbers in the table variable. The invariant is that after each pass of the outer loop, the largest unsorted element 'bubbles up' to its correct position at the end of the unsorted portion.

Pseudocode:

FUNCTION BubbleSort(numberList):
  Parse numberList into an array
  n = length(array)

  IF n <= 1 THEN RETURN numberList

  FOR i from 0 to n-2:
    swapped = false
    FOR j from 0 to n-2-i:
      IF array[j] > array[j+1] THEN
        swap array[j] and array[j+1]
        swapped = true
    IF swapped is false THEN BREAK

  Reconstruct sorted array into a string
  RETURN sorted string