Lua - Bubble Sort
Bubble sort is a classic and most popular sorting algorithm to begin learning on sorting technique. In bubble sort, we repeatedly steps into the list while comparing adjacent elememts and swapping them if they are not in correct order. Eventually, larger element bubbles out to the end of the list.
main.lua
-- function to sort a list using bubble sort
function bubble_sort(list)
-- length of the list
local n = #list
-- flag to check if any element was swapped in a pass
local swapped
-- repeat till there is any swap during a pass
repeat
-- reset flag in the beginning
swapped = false
-- loop through list
for i = 1, n - 1 do
-- compare adjacent elements
if list[i] > list[i + 1] then
-- swap elements
list[i], list[i + 1] = list[i + 1], list[i]
-- set flag as true
swapped = true
end
end
-- as largest element is moved to end, reduce the list
n = n - 1
until not swapped
-- list is sorted, return it
return list
end
local numbers = {5, 1, 4, 2, 8}
local sorted = bubble_sort(numbers)
print("Sorted list:", table.concat(sorted, ", "))
Output
When we run the above program, we will get the following output−
Sorted list: 1, 2, 4, 5, 8
Working of Bubble Sort
Compare Adjacent Elements − We're repeatedly steps into the list comparing the adjacent elements.
Swap Adjacent Elements − If elements being compared are not in ascending order, swap them.
Iteration − In single pass of iteration, we compare and swap each number till the end of the list.
Bubbling − When single pass is over, the largest element is bubbled out to the end the list at being its correct position.
Repeat the process − The above steps are repeated for remaining unsorted list until no swap occurs during a single pass which means a list is sorted completely.
Time Complexity
Worst Case and Average Case − O(n2), where n is number of elements. We may need to perform multiple iterations through all elements of a list in case list is reversely sorted or mostly are scrambled.
Best Case O(n) − O(n) when list is sorted as we'll iterate only once through the list.
Space Complexity
O(1) − Space complexity of bubble sort is constant as it requires a fixed amount of extra space required for temporary variable swapped
When to use Bubble Sort
Bubble sort is not preferred for large set of data as its average time complexity is O(n2). But being easy to learn and easy to implement, it is still applicable and is used in following areas −
Educational Purpose − Being easy to illustrate, bubble sort is used to showcase sorting algorithm.
Small Set of Data − In case of smaller set of data, bubble sort is preferred instead of more complex counterparts.
Nearly Sorted Data − When a list is nearly sorted, the time complexity of Bubble sort is quite good, nearing to O(n).