Linearithmic Time Complexity

Linearithmic time complexity with example

Linearithmic time complexity refers to algorithms whose running time grows in proportion to ( n ) multiplied by ( \log n ). This is more efficient than ( O(n^2) ) but slower than ( O(n) ).

The O(n log n) time complexity is common in efficient sorting algorithms, where the input list is broken down into smaller parts and each part is processed. As the input size increases, the number of operations grows linearly, but with an additional logarithmic factor due to the splitting and merging steps.

Example: Merge Sort

Suppose you have the following unsorted list of numbers:

[8, 3, 5, 2, 7, 6, 1, 4]

You want to sort this list in ascending order using Merge Sort, which is an example of an O(n log n) algorithm.

How Merge Sort Works

  1. Divide the array into two halves:
    • Left: [8, 3, 5, 2]
    • Right: [7, 6, 1, 4]
  2. Recursively divide the left half [8, 3, 5, 2]:
    • Left: [8, 3]
    • Right: [5, 2]
  3. Continue dividing:
    • [8, 3] -> [8], [3]
    • [5, 2] -> [5], [2]
  4. Merge the divided arrays:
    • Merge [8] and [3] → Result: [3, 8]
    • Merge [5] and [2] → Result: [2, 5]
  5. Merge [3, 8] and [2, 5] → Result: [2, 3, 5, 8]
  6. Repeat the process for the right half [7, 6, 1, 4]:
    • Left: [7, 6], Right: [1, 4]
    • [7, 6] -> [7], [6]
    • [1, 4] -> [1], [4]
    • Merge [7] and [6] → Result: [6, 7]
    • Merge [1] and [4] → Result: [1, 4]
    • Merge [6, 7] and [1, 4] → Result: [1, 4, 6, 7]
  7. Finally, merge the two sorted halves:
    • Left: [2, 3, 5, 8]
    • Right: [1, 4, 6, 7]
    • Merge them → Result: [1, 2, 3, 4, 5, 6, 7, 8]

The list is now sorted in O(n log n) time.

Why is Merge Sort O(n log n)?

  • The log n part comes from repeatedly dividing the list into halves.
  • The n part comes from merging all the sublists back together.
  • For a list of size ( n ):
  • It takes log₂(n) steps to break the list down.
  • Each merging step takes ( n ) operations.

Thus, the total time complexity is O(n log n).

Real-Life Analogy

Imagine you have a large pile of unsorted papers and you want to organize them alphabetically. Instead of sorting the entire pile at once, you:

  1. Divide the pile into smaller, more manageable stacks.
  2. Sort each smaller stack individually.
  3. Merge the sorted stacks together one by one.

By breaking the task into smaller chunks and merging them efficiently, you sort the entire pile in less time than if you tried to sort everything all at once. This is similar to how O(n log n) algorithms like Merge Sort operate.