Sorting
Merge Sort (Top-Down)
Split the array recursively, sort each half, then merge two sorted runs into one sorted result.
Algorithm
The checked-in replay follows the same small input and final output across all 21 DSA books, so this Scala DSA implementation can be compared directly with the other languages.
Basic Implementation
basic.scala
object Main {
def mergeSort(values: List[Int]): List[Int] = {
if (values.length <= 1) return values
val (leftRaw, rightRaw) = values.splitAt(values.length / 2)
val left = mergeSort(leftRaw)
val right = mergeSort(rightRaw)
merge(left, right)
}
def merge(left: List[Int], right: List[Int]): List[Int] = (left, right) match {
case (Nil, _) => right
case (_, Nil) => left
case (l :: ls, r :: rs) =>
if (l <= r) l :: merge(ls, right) else r :: merge(left, rs)
}
def main(args: Array[String]): Unit = {
val arr = List(5, 1, 4, 2, 8)
println(mergeSort(arr).mkString("[", ", ", "]"))
}
}
Complexity
- Time: O(n log n)
- Space: O(n)
- Stable: yes
Implementation notes
- Keep the explicit algorithmic steps instead of calling a standard-library sort. The replay is meant to expose comparisons, movement, and recursion.
- The implementation is intentionally compact for learning and replay, not a production sorting utility.
divide and conquer
Each recursive call solves a smaller sorted subproblem.
merge step
Two sorted halves are combined by repeatedly taking the smaller front item.