Lua - Merge Sort



Merge Sort is a divide and conquer algorithm. We divides a list in two sublists till each sublist has only one element. Then we merge each sublist to create a sorted list.

main.lua

-- function to merge two sublists
function merge(left, right)
   local result = {}  -- table for merge results
   local i = 1  -- index to track left list
   local j = 1  -- index to track right list
   -- compare elements of both lists, add the smaller one to the merged result
   while i <= #left and j <= #right do
      if left[i] < right[j] then
         table.insert(result, left[i])
         i = i + 1
      else
         table.insert(result, right[j])
         j = j + 1
      end
   end

   -- in case left list is not covered fully
   while i <= #left do
      table.insert(result, left[i])
      i = i + 1
   end

   -- in case right list is not covered fully
   while j <= #right do
      table.insert(result, right[j])
      j = j + 1
   end

   -- return the merged and sorted list
   return result
end

-- function to sort a list using merge sort
function merge_sort(list)
   local n = #list -- length of the list
   if n <= 1 then  -- if list is of single element
      return list     -- return list as it is already sorted
   end
   local mid = math.floor(n / 2) -- get the mid point
   local left = {} -- left sublist
   local right = {} -- right sublist
   for i = 1, mid do -- fill left sublist
      table.insert(left, list[i])
   end
   for i = mid + 1, n do -- fill right sublist
      table.insert(right, list[i])
   end
   -- merge list after sorting recursively
   return merge(merge_sort(left), merge_sort(right))
end

-- Example usage:
local numbers = {5, 1, 4, 2, 8}
local sorted = merge_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 Merge Sort

  • Divide − We're dividing the list recursively in two halves until each sublist is having a single element.

  • Conquer − When a list of one element is reached, it is implicitly sorted.

  • Merge − Once sorted, algorithm merges the sorted sublists to produce a new sorted sublist.

merge function

  • merge − function is core of the merge sort algorithm. We're passing two sorted sublists to it and it returns the merged and sorted list.

  • We're iterating both lists simultaneously comparing each elements and appending the smaller to the result list.

  • We're then incrementing the index of the table from which the smaller element was taken.

  • Once a smaller list is exhausted, we're appending remaining element of the other list to the result list.

merge_sort function

  • merge_sort − function makes recursive calls. As best case, size of 1 is taken, which means list is sorted.

  • Otherwise, we're computing the mid point to divide the list into two halves, left from start to middle and right from middle+1 to the last element.

  • Now merge_sort is called recursively on both sublists to sort them.

  • Finally merge function is called to merge the sorted sublists into a single sorted list as result.

Time Complexity

  • O(n log n) −, where n is number of elements. Merge sort provides a consistent performance in all worst-case, average and best-case scenario. Division step takes O(logn) time and merge is of O(n) time.

Space Complexity

  • O(n) − Space complexity of merge sort is dependent directly on number of elements as it need to store temporary sublists into the storage.

When to use Merge Sort

Merge sort is a very efficient sorting algorithm with a consistent time complexity of O(n log n) −

  • Large Data Sets − Merge sort is very efficient with large set of data having time complexity of O(n log n).

  • External Sorting − In case of data which is not getting loaded in memory fully, merge sort is applible, it can read only chunks of data from disk as required.

  • Stability − In case, we need to preserve order of equal elements in the list, merge sort is aptly suitable as it is a stable algorithm and preserve the order of equal elements in the sorted list.

Advertisements