Quick Sort - Golang
package main
import "fmt"
func main() {
arr := []int{4, 1, 3, 2, 5}
result := QuickSort(arr)
fmt.Println(result)
}
func QuickSort(arr []int) []int {
if len(arr) <= 1 {
return arr
}
return quickSort(arr, 0, len(arr)-1)
}
func quickSort(arr []int, low, high int) []int {
if low >= high {
return arr
}
partitionVal := partition(arr, low, high)
arr = quickSort(arr, low, partitionVal-1)
arr = quickSort(arr, partitionVal+1, high)
return arr
}
func partition(arr []int, low, high int) int {
pivot := arr[high]
i := low - 1
for j := low; j < high; j++ {
if arr[j] < pivot {
i += 1
arr[i], arr[j] = arr[j], arr[i]
}
}
arr[i+1], arr[high] = arr[high], arr[i+1]
return i + 1
}
The above program will print the following output:
[1 2 3 4 5]