-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsort-an-array.go
48 lines (40 loc) · 1010 Bytes
/
sort-an-array.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
package main
import (
"fmt"
"math/rand"
)
// source: https://leetcode.com/problems/sort-an-array/
func sortArray(data []int) []int {
var doSort func(data []int, l, r int)
doSort = func(data []int, l, r int) {
if l < r {
p := randomPartition(data, l, r)
doSort(data, l, p-1)
doSort(data, p+1, r)
}
}
doSort(data, 0, len(data)-1)
return data
}
// randomPartition implements randomized partition algorithm by randomly selecting pivot
func randomPartition(data []int, l, r int) int {
x := rand.Intn(r-l) + l
data[x], data[r] = data[r], data[x]
i, pivot := l-1, data[r]
for j := l; j < r; j++ {
if data[j] <= pivot {
i++
data[i], data[j] = data[j], data[i]
}
}
data[i+1], data[r] = data[r], data[i+1]
return i + 1
}
func main() {
// Example 1
var nums1 []int = []int{5, 2, 3, 1}
fmt.Println("Expected: [1,2,3,5] Output: ", sortArray(nums1))
// Example 2
var nums2 []int = []int{5, 1, 1, 2, 0, 0}
fmt.Println("Expected: [0,0,1,1,2,5] Output: ", sortArray(nums2))
}