Skip to content

Instantly share code, notes, and snippets.

@max-mulawa
Created April 21, 2011 13:14
Show Gist options
  • Save max-mulawa/934443 to your computer and use it in GitHub Desktop.
Save max-mulawa/934443 to your computer and use it in GitHub Desktop.
Bubble Sort in T-SQL
IF OBJECT_ID('tempdb..#NumbersArray') IS NOT NULL
DROP TABLE #NumbersArray
GO
--Create T-SQL version of number array look-like
CREATE TABLE #NumbersArray
(
ArrayIndex Int PRIMARY KEY CLUSTERED,
Value Int
)
GO
INSERT INTO #NumbersArray(ArrayIndex, Value)
SELECT 0,5
UNION ALL
SELECT 1,1
UNION ALL
SELECT 2,3
UNION ALL
SELECT 3,4
UNION ALL
SELECT 4,2
SELECT 'BEFORE bubble sort', *
FROM #NumbersArray
ORDER BY ArrayIndex
DECLARE @currentElementArrayIndex Int
, @sortFromArrayIndex Int
, @swapOccured Bit
SET @swapOccured = 1
SET @sortFromArrayIndex = (SELECT COUNT(*)-1 FROM #NumbersArray)
WHILE (@swapOccured = 1) --Continue iteration only if element swap occured
BEGIN
SET @swapOccured = 0
SET @currentElementArrayIndex = 0
WHILE (@currentElementArrayIndex < @sortFromArrayIndex)
BEGIN
DECLARE @val Int
DECLARE @val2 Int
SET @val = (SELECT Value
FROM #NumbersArray
WHERE ArrayIndex = @currentElementArrayIndex)
SET @val2 = (SELECT Value
FROM #NumbersArray
WHERE ArrayIndex = @currentElementArrayIndex+1)
IF @val > @val2
BEGIN
--SWAP
UPDATE #NumbersArray
SET Value = @val2
WHERE ArrayIndex = @currentElementArrayIndex
UPDATE #NumbersArray
SET Value = @val
WHERE ArrayIndex = @currentElementArrayIndex+1
SET @swapOccured = 1
END
SET @currentElementArrayIndex = @currentElementArrayIndex+1
END
--SELECT * FROM #NumbersArray ORDER BY ArrayIndex
SET @sortFromArrayIndex = @sortFromArrayIndex - 1
END
SELECT 'AFTER bubble sort',*
FROM #NumbersArray
ORDER BY ArrayIndex
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment