Created
March 8, 2019 18:45
-
-
Save lordkebab/b02c9087875be665b86bd666f6a2a034 to your computer and use it in GitHub Desktop.
quicksort implementation in go
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import "fmt" | |
func partition(n []int) int { | |
low := 0 | |
tail := low - 1 | |
high := len(n) - 1 | |
pivot := n[high] | |
for i := 0; i <= high; i++ { | |
if n[i] < pivot { | |
tail++ | |
n[i], n[tail] = n[tail], n[i] | |
} | |
} | |
tail++ | |
n[tail], n[high] = n[high], n[tail] | |
return tail | |
} | |
func quicksort(n []int, low, high int) []int { | |
if low < high { | |
idx := partition(n) | |
quicksort(n[:idx], 0, len(n[:idx])-1) | |
quicksort(n[idx+1:], 0, len(n[idx+1:])-1) | |
} | |
return n | |
} | |
func main() { | |
n := []int{9, 7, 5, 11, 12, 2, 14, 3, 10, 6, 88, 3, -1, 55} | |
fmt.Println(n, " sorted-> ", quicksort(n, 0, len(n)-1)) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment