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
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).
Solution
/**
* @param {number[]} nums
* @return {number[]}
*/
var sortArray = function (nums) {
//If the array is 2 or less, return the array
if (nums.length <= 1) return nums;
var n = nums.length;
for (var i = 0; i <n-1; i++) {
//Find the minimum value in the array
var min = i;
for (var j = i+1; j < n; j++ ) {
//If the value is less than the minimum value, set the minimum value to the current value
if (nums[j] < nums[min]) {
min = j;
}
}
//Swap the minimum value with the current value
var temp = nums[i];
//Swap the values
nums[i] = nums[min];
//Set the minimum value to the current value
nums[min] = temp;
}
return nums;
};