Wiggle Sort
Description
null
Solution(javascript)
// /** 1: sort O(nlog(n))
// * @param {number[]} nums
// * @return {void} Do not return anything, modify nums in-place instead.
// */
// const wiggleSort = function (nums) {
// nums.sort((a, b) => a - b)
// for (let i = 1; i + 1 < nums.length; i += 2) {
// const temp = nums[i]
// nums[i] = nums[i + 1]
// nums[i + 1] = temp
// }
// }
/** 2: sort O(nlog(n))
* @param {number[]} nums
* @return {void} Do not return anything, modify nums in-place instead.
*/
const wiggleSort = function (nums) {
const swap = (i, j) => {
const temp = nums[i]
nums[i] = nums[j]
nums[j] = temp
}
for (let i = 0; i + 1 < nums.length; i += 1) {
if (i % 2 === 0) {
if (nums[i] > nums[i + 1]) {
swap(i, i + 1)
}
} else if (nums[i] < nums[i + 1]) {
swap(i, i + 1)
}
}
}