An interactive visualization of the merge sort divide-and-conquer algorithm. Watch how the array is recursively split into halves and then merged back together in sorted order.
Divide and Conquer LeetCode 912 ↗ Mediumnums, sort the array in ascending order and return it.fun mergeSort(arr: List<Int>): List<Int> { if (arr.size <= 1) { return arr } val mid = arr.size / 2 val left = mergeSort(arr.subList(0, mid)) val right = mergeSort(arr.subList(mid, arr.size)) return merge(left, right)}fun merge(left: List<Int>, right: List<Int>): List<Int> { val result = mutableListOf<Int>() var i = 0; var j = 0 while (i < left.size && j < right.size) { if (left[i] <= right[j]) { result.add(left[i]) i++ } else { result.add(right[j]) j++ } } result.addAll(left.subList(i, left.size)) result.addAll(right.subList(j, right.size)) return result}
Merge Sort follows the divide and conquer paradigm: divide the array into two halves, conquer by recursively sorting each half, then combine the two sorted halves by merging them together. The merging step is efficient because both halves are already sorted, so we just need to compare the front elements and pick the smaller one.
mid = len(arr) // 2 and split the array into arr[:mid] and arr[mid:].i and j to walk through the left and right halves, always picking the smaller element.
The array is split into log n levels, and at each level we do O(n) work
to merge all subarrays. The extra space comes from the temporary arrays created during merging.
Merge Sort is a stable sort and guarantees O(n log n) performance
regardless of the input order.