Sort an Array
Sort an Array
SortingDivide and Conquer
Problem Statement
Given an array of integers nums
, sort the array in ascending order and return it.
You must solve the problem without using any built-in sorting functions.
Example
Example 1:
nums: [5, 2, 3, 1]
Output: [1, 2, 3, 5]
Solution
A standard and efficient way to solve this problem is by using the Merge Sort algorithm. It's a classic "Divide and Conquer" algorithm with a time complexity of O(n log n).
Merge Sort works by recursively splitting the array into halves until each subarray contains a single element. Then, it merges these subarrays back together in sorted order.
Algorithm Steps (Merge Sort)
- Recursively divide the array into two halves until you reach subarrays of size 1.
- Merge the smaller sorted subarrays back together.
- Create two temporary arrays for the left and right halves.
- Compare elements from the left and right halves and place the smaller element into the original array.
- Continue until one of the halves is exhausted.
- Copy any remaining elements from the non-exhausted half.
Merge Sort Visualization
5
2
3
1
8
7
6
4
Ready to sort.
Sort an Array (Merge Sort)