#912

Sort an Array

Medium Merge sort

  1. Read
  2. Understand
  3. Hints
  4. Approach
  5. Solution
  6. Solved

?The problem

Sort an integer array in ascending order in O(n log n) without built-in sort functions.

This is a short summary in our own words. Read the full statement and examples on LeetCode: open problem ↗

◎Understanding

Really asking: sort in O(n log n) without library sort.

Why this works: merge sort always splits evenly, so it never degrades like a naive quicksort on sorted input.

Example: [5, 2, 3, 1]

split → [5, 2] [3, 1]sort halves → [2, 5] [1, 3]merge → [1, 2, 3, 5]

✦Hints open one at a time

↗Approach

</>Solution (Java)

!Common mistake

Using quicksort with the first element as pivot — it times out on already-sorted input.

Solve on LeetCode ↗
Complexity
  • Time: O(n log n).
  • Space: O(n).
Topic: Sorting
🎬 Episodes 24–28: video coming soon