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 functions in O(nlog(n)) time complexity and with the smallest space complexity possible.
Example 1:
Input: nums = [5,2,3,1]
Output: [1,2,3,5]
Explanation: After sorting the array, the positions of some numbers are not changed (for example, 2 and 3), while the positions of other numbers are changed (for example, 1 and 5).
Example 2:
Input: nums = [5,1,1,2,0,0]
Output: [0,0,1,1,2,5]
Explanation: Note that the values of nums are not necessairly unique.
Constraints:
1 <= nums.length <= 5 * 104
-5 * 104 <= nums[i] <= 5 * 104
Code
Heap Sort
Time Complexity: O(NlogN), Space Complexity: O(N)
Make heap is O(N), but heap sort is still O(NlogN).
Merge Sort (Recursive)
Time Complexity: O(NlogN), Space Complexity: O(N)
Counting Sort
Time Complexity: O(N+K), Space Complexity: O(N+K), where K is MAX。
Radix Sort
Time Complexity: O(log2N∗(N+K)), Space Complexity: O(N+K), where K is MAX。
要注意 while((MAX >> (pos * bits)) > 0) ,若 bits 設太大(例如 16)就會有可能產生 left shift 32 的狀況,這對於 int 來說是 undefined behavior。
還有要注意 for(int i = n - 1; i >= 0; i--),這樣才可以保證是 stable sort。