# Thread: [Lua] Bubble Sort Algorithm

1. ## [Lua] Bubble Sort Algorithm

Here are two functions written in Lua that use the bubble sort algorithm. The input parameter on both is an array, in my function I didn't bother to check if A) it's an array or B) more specifically if it's a number array. These two functions are very simple and pretty self explanatory as I've tried to include quite a bit of notes:

Code:
```function bubbleLowestToHighest(input)

-- The array that will be returned
sortedArray = input

-- The variable that will tell us if the array is sorted
isSorted = false

-- Loop until the array is sorted
while isSorted == false do

movedElements = 0

-- Loop through each element in the array(minus the last element)
for x = 1, table.getn(input) - 1, 1 do

-- If the element we're on is greater than the element after it
-- The swap index of the two elements
if input[x] > input[x + 1] then

movedElements = movedElements + 1

testedElement = input[x]

input[x] = input[x + 1]
input[x + 1] = testedElement
end

end

if movedElements == 0 then
isSorted = true
end

end

return sortedArray

end

function bubbleHighestToLowest(input)

-- The array that will be returned
sortedArray = input

-- The variable that will tell us if the array is sorted
isSorted = false

-- Loop until the array is sorted
while isSorted == false do

movedElements = 0

-- Loop through each element in the array(minus the last element)
for x = 1, table.getn(input) - 1, 1 do

-- If the element we're on is greater than the element after it
-- The swap index of the two elements
if input[x] < input[x + 1] then

movedElements = movedElements + 1

testedElement = input[x]

input[x] = input[x + 1]
input[x + 1] = testedElement
end

end

if movedElements == 0 then
isSorted = true
end

end

return sortedArray

end```

#### Posting Permissions

• You may not post new threads
• You may not post replies
• You may not post attachments
• You may not edit your posts
•

Featured