go: add «912. Sort an Array»

Signed-off-by: Matej Focko <me@mfocko.xyz>
This commit is contained in:
Matej Focko 2024-07-25 12:06:39 +02:00
parent 4cf960b73b
commit 31c882dfcd
Signed by: mfocko
SSH key fingerprint: SHA256:icm0fIOSJUpy5+1x23sfr+hLtF9UhY8VpMC7H4WFJP8

42
go/sort-an-array.go Normal file
View 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
}