Skip to content

Commit d3f521a

Browse files
author
Yi Gu
committed
[Sort] add Solution to Wiggle Sort I, II
1 parent acf5bab commit d3f521a

File tree

2 files changed

+69
-0
lines changed

2 files changed

+69
-0
lines changed

Sort/WiggleSort.swift

Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
1+
/**
2+
* Question Link: https://leetcode.com/problems/wiggle-sort/
3+
* Primary idea: Iterate the array and swap the largest one to the middle
4+
* Time Complexity: O(n), Space Complexity: O(1)
5+
*/
6+
7+
class WiggleSort {
8+
func wiggleSort(inout nums: [Int]) {
9+
guard nums.count >= 2 else {
10+
return
11+
}
12+
13+
for i in 1.stride(to: nums.count, by: 2) {
14+
let largestIndex = _getLargest(&nums, i - 1, i, i + 1)
15+
if i != largestIndex {
16+
_swap(&nums, largestIndex, i)
17+
}
18+
}
19+
}
20+
21+
private func _swap(inout nums: [Int], _ p: Int, _ q: Int) {
22+
let temp = nums[p]
23+
nums[p] = nums[q]
24+
nums[q] = temp
25+
}
26+
27+
private func _getLargest(inout nums: [Int], _ x: Int, _ y: Int, _ z: Int) -> Int {
28+
let xVal = _isValid(x, nums.count) ? nums[x] : Int.min
29+
let yVal = _isValid(y, nums.count) ? nums[y] : Int.min
30+
let zVal = _isValid(z, nums.count) ? nums[z] : Int.min
31+
let maxVal = max(xVal, yVal, zVal)
32+
33+
if maxVal == xVal {
34+
return x
35+
} else if maxVal == yVal {
36+
return y
37+
} else {
38+
return z
39+
}
40+
}
41+
42+
private func _isValid(index: Int, _ len: Int) -> Bool {
43+
return index >= 0 && index < len
44+
}
45+
}

Sort/WiggleSortII.swift

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
/**
2+
* Question Link: https://leetcode.com/problems/wiggle-sort-ii/
3+
* Primary idea: Sort and re-arrange the array
4+
* Time Complexity: O(nlogn), Space Complexity: O(n)
5+
*/
6+
7+
class WiggleSortII {
8+
func wiggleSort(inout nums: [Int]) {
9+
let temp = nums.sort({$0 < $1})
10+
11+
var m = temp.count
12+
var n = (m + 1) / 2
13+
14+
for i in 0 ..< nums.count {
15+
if i & 1 == 0 {
16+
n = n - 1
17+
nums[i] = temp[n]
18+
} else {
19+
m = m - 1
20+
nums[i] = temp[m]
21+
}
22+
}
23+
}
24+
}

0 commit comments

Comments
 (0)