
- Lua Tutorial
- Lua - Home
- Lua Basics
- Lua - Overview
- Lua - Environment
- Lua - Basic Syntax
- Lua - Comments
- Lua - Print Hello World
- Lua - Variables
- Lua - Data Types
- Lua - Operators
- Lua - Loops
- Lua - Generic For
- Lua - Decision Making
- Lua - Date and Time
- Lua Functions
- Lua - Functions
- Lua - Multiple Results
- Lua - Named Arguments
- Lua - Default/Optional Arguments
- Lua - Closures
- Lua - Uses of Closures
- Lua - Local Functions
- Lua - Anonymous Functions
- Lua - Functions in Table
- Lua - Proper Tail Calls
- Lua Strings
- Lua - Strings
- Lua - String Concatenation
- Lua - Loop Through String
- Lua - String to Int
- Lua - Split String
- Lua - Check String is NULL
- Lua Arrays
- Lua - Arrays
- Lua - Multi-dimensional Arrays
- Lua - Array Length
- Lua - Iterating Over Arrays
- Lua - Slicing Arrays
- Lua - Sorting Arrays
- Lua - Merging Arrays
- Lua - Sparse Arrays
- Lua - Searching Arrays
- Lua - Resizing Arrays
- Lua - Array to String Conversion
- Lua - Array as Stack
- Lua - Array as Queue
- Lua - Array with Metatables
- Lua - Immutable Arrays
- Lua - Shuffling Arrays
- Lua Iterators
- Lua - Iterators
- Lua - Stateless Iterators
- Lua - Stateful Iterators
- Lua - Built-in Iterators
- Lua - Custom Iterators
- Lua - Iterator Closures
- Lua - Infinite Iterators
- Lua - File Iterators
- Lua - Table Iterators
- Lua - Numeric Iterators
- Lua - Reverse Iterators
- Lua - Filter Iterators
- Lua - Range Iterators
- Lua - Chaining Iterators
- Lua Tables
- Lua - Tables
- Lua - Tables as Arrays
- Lua - Tables as Dictionaries
- Lua - Tables as Sets
- Lua - Table Length
- Lua - Table Iteration
- Lua - Table Constructors
- Lua - Loop through Table
- Lua - Merge Tables
- Lua - Nested Tables
- Lua - Accessing Table Fields
- Lua - Copy Table by Value
- Lua - Get Entries from Table
- Lua - Table Metatables
- Lua - Tables as Objects
- Lua - Table Inheritance
- Lua - Table Cloning
- Lua - Table Sorting
- Lua - Table Searching
- Lua - Table Serialization
- Lua - Weak Tables
- Lua - Table Memory Management
- Lua - Tables as Stacks
- Lua - Tables as Queues
- Lua - Sparse Tables
- Lua Lists
- Lua - Lists
- Lua - Inserting Elements into Lists
- Lua - Removing Elements from Lists
- Lua - Iterating Over Lists
- Lua - Reverse Iterating Over Lists
- Lua - Accessing List Elements
- Lua - Modifying List Elements
- Lua - List Length
- Lua - Concatenate Lists
- Lua - Slicing Lists
- Lua - Sorting Lists
- Lua - Reversing Lists
- Lua - Searching in Lists
- Lua - Shuffling List
- Lua - Multi-dimensional Lists
- Lua - Sparse Lists
- Lua - Lists as Stacks
- Lua - Lists as Queues
- Lua - Functional Operations on Lists
- Lua - Immutable Lists
- Lua - List Serialization
- Lua - Metatables with Lists
- Lua Modules
- Lua - Modules
- Lua - Returning Functions from Modules
- Lua - Returning Functions Table from Modules
- Lua - Module Scope
- Lua - SubModule
- Lua - Module Caching
- Lua - Custom Module Loaders
- Lua - Namespaces
- Lua - Singleton Modules
- Lua - Sharing State Between Modules
- Lua - Module Versioning
- Lua Metatables
- Lua - Metatables
- Lua - Chaining Metatables
- Lua - Proxy Tables with Metatables
- Lua - Use Cases for Proxy Table
- Lua - Delegation and Tracing via Proxy Tables
- Lua - Metatables vs Metamethods
- Lua - Fallback Mechanisms in Metatables
- Lua - Fallback Cases for Indexing Metamethods
- Lua - Fallback Cases for Arithmetic and Comparison Metamethods
- Lua - Fallback Cases for Other Metamethods
- Lua - Customizing Behavior with Metatables
- Lua - Controlling Table Access
- Lua - Overloading Operators
- Lua - Customizing Comparisons
- Lua - Making a Table Callable
- Lua - Customizing String Representation
- Lua - Controlling Metatable Access
- Lua Coroutines
- Lua - Coroutines
- Lua - Coroutine Lifecycle
- Lua - Communication Between Coroutines
- Lua - Coroutines vs Threads
- Lua - Chaining Coroutines
- Lua - Chaining Coroutines With Scheduler
- Lua - Chaining Coroutines Using Queues
- Lua - Coroutine Control Flow
- Lua - Nested Coroutines
- Lua File Handling
- Lua - File I/O
- Lua - Opening Files
- Lua - Modes for File Access
- Lua - Reading Files
- Lua - Writing Files
- Lua - Closing Files
- Lua - Renaming Files
- Lua - Deleting Files
- Lua - File Buffers and Flushing
- Lua - Reading Files Line by Line
- Lua - Binary File Handling
- Lua - File Positioning
- Lua - Appending to Files
- Lua - Error Handling in File Operations
- Lua - Checking if File exists
- Lua - Checking if File is Readable
- Lua - Checking if File is Writable
- Lua - Checking if File is ReadOnly
- Lua - File Descriptors
- Lua - Creating Temporary Files
- Lua - File Iterators
- Lua - Working with Large Files
- Lua Advanced
- Lua - Error Handling
- Lua - Debugging
- Lua - Garbage Collection
- Lua - Object Oriented
- Lua - Web Programming
- Lua - Database Access
- Lua - Game Programing
- Sorting Algorithms
- Lua - Bubble Sort
- Lua - Insertion Sort
- Lua - Selection Sort
- Lua - Merge Sort
- Lua - Quick Sort
- Searching Algorithms
- Lua - Linear Search
- Lua - Binary Search
- Lua - Jump Search
- Lua - Interpolation Search
- Regular Expression
- Lua - Pattern Matching
- Lua - string.find() method
- Lua - string.gmatch() method
- Lua - string.gsub() method
- Lua Useful Resources
- Lua - Quick Guide
- Lua - Useful Resources
- Lua - Discussion
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.