go: add «912. Sort an Array»
Signed-off-by: Matej Focko <me@mfocko.xyz>
This commit is contained in:
parent
4cf960b73b
commit
31c882dfcd
1 changed files with 42 additions and 0 deletions
42
go/sort-an-array.go
Normal file
42
go/sort-an-array.go
Normal file
|
@ -0,0 +1,42 @@
|
||||||
|
package main
|
||||||
|
|
||||||
|
func sortArray(nums []int) []int {
|
||||||
|
swap := func(i, j int) {
|
||||||
|
nums[i], nums[j] = nums[j], nums[i]
|
||||||
|
}
|
||||||
|
|
||||||
|
partition := func(lower, upper int) (int, int) {
|
||||||
|
pivot := nums[(lower+upper)/2]
|
||||||
|
|
||||||
|
lt, eq, gt := lower, lower, upper
|
||||||
|
|
||||||
|
for eq <= gt {
|
||||||
|
if nums[eq] < pivot {
|
||||||
|
swap(eq, lt)
|
||||||
|
lt++
|
||||||
|
eq++
|
||||||
|
} else if nums[eq] > pivot {
|
||||||
|
swap(eq, gt)
|
||||||
|
gt--
|
||||||
|
} else {
|
||||||
|
eq++
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return lt, gt
|
||||||
|
}
|
||||||
|
|
||||||
|
var quicksort func(int, int)
|
||||||
|
quicksort = func(lower, upper int) {
|
||||||
|
if lower >= upper || lower < 0 || upper < 0 {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
lt, gt := partition(lower, upper)
|
||||||
|
quicksort(lower, lt-1)
|
||||||
|
quicksort(gt+1, upper)
|
||||||
|
}
|
||||||
|
|
||||||
|
quicksort(0, len(nums)-1)
|
||||||
|
return nums
|
||||||
|
}
|
Loading…
Reference in a new issue