LeetCode/go/sort-an-array.go

43 lines
687 B
Go
Raw Normal View History

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
}