WiggleSort [摆动排序]
# 介绍
摆动排序,是队列满足波浪式的顺序。
# 实现
# JavaScript
/*
* Wiggle sort sorts the array into a wave like array.
* An array ‘arr[0..n-1]’ is sorted in wave form if arr[0] >= arr[1] <= arr[2] >= arr[3] <= arr[4] >= …..
*/
export const wiggleSort = function (arr) {
for (let i = 0; i < arr.length; ++i) {
const shouldNotBeLessThan = i % 2
const isLessThan = arr[i] < arr[i + 1]
if (shouldNotBeLessThan && isLessThan) {
[arr[i], arr[i + 1]] = [arr[i + 1], arr[i]]
}
}
return arr
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
2
3
4
5
6
7
8
9
10
11
12
13
14
15
# 参考
编辑 (opens new window)
上次更新: 2022/05/10, 23:46:22