mirror of
https://gitlab.com/mfocko/LeetCode.git
synced 2024-11-10 00:09:06 +01:00
42 lines
687 B
Go
42 lines
687 B
Go
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
|
|
}
|