Skip to content

Instantly share code, notes, and snippets.

@patterns
Created October 7, 2016 05:33
Show Gist options
  • Save patterns/f376bb6865a349f1498d185dad27870d to your computer and use it in GitHub Desktop.
Save patterns/f376bb6865a349f1498d185dad27870d to your computer and use it in GitHub Desktop.
Quick sort recursive
package main
import (
"fmt"
"bufio"
"os"
)
//see Cracking Code Interview
//practice quick sort (recursive)
//input - size n on first line and space delimited item values on second line
func main() {
var n int
var v int
scanner := bufio.NewReader(os.Stdin)
_, err := fmt.Fscanf(scanner, "%d\n", &n)
if err != nil {
panic(err.Error())
}
a := make([]int, n)
for i :=0; i <n-1; i++ {
_, _ = fmt.Fscanf(scanner, "%d ", &v)
a[i] = v
}
_, _ = fmt.Fscanf(scanner, "%d\n", &v)
a[n-1] = v
quicksort(a, 0, n -1)
fmt.Printf("%v\n", a)
}
func quicksort(a []int, left int, right int) {
if left >= right {
return
}
pivot := a[left + (right - left)/2]
index := partition(a, left, right, pivot)
quicksort(a, left, index-1)
quicksort(a, index, right)
}
func partition(a []int, left int, right int, pivot int) int {
i := left
j := right
//The bookend indices move toward the middle
for ; ; {
if i >= j {
break
}
//Move left towards the right until a value is >pivot
for ; a[i] < pivot && i <j; {
//Move left towards the right until a value is >pivot
i++
}
for ; a[j] > pivot && j >i; {
//Move right towards the left until a value is <pivot
j--
}
if i <= j {
//Indices should be resting on values that need swap
swap(a, i, j)
i++
j--
}
}
return i
}
func swap(a []int, i int, j int) {
tmp := a[i]
a[i] = a[j]
a[j] = tmp
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment