Sort an Array
Description
Given an array of integers nums
, sort the array in ascending order.
Example 1:
Input: nums = [5,2,3,1] Output: [1,2,3,5]
Example 2:
Input: nums = [5,1,1,2,0,0] Output: [0,0,1,1,2,5]
Constraints:
1 <= nums.length <= 50000
-50000 <= nums[i] <= 50000
Solution(javascript)
/**
* @param {number[]} nums
* @return {number[]}
*/
var sortArray = function(arr) {
const swap = (arr, i, j) => {
const temp = arr[i]
arr[i] = arr[j]
arr[j] = temp
}
const partition = (lo, hi) => {
let i = lo
let j = hi + 1
while (true) {
while (arr[++i] < arr[lo]) {
if (i === hi) {
break
}
}
while (arr[--j] > arr[lo]) {
if (j === lo) {
break
}
}
if (i >= j) {
break
}
swap(arr, i, j)
}
swap(arr, lo, j)
return j
}
const sort = (left, right) => {
if (left >= right) {
return arr
}
const pivot = partition(left, right)
sort(left, pivot - 1)
sort(pivot + 1, right)
return arr
}
return sort(0, arr.length - 1)
};