Quick Sort With Slices
package main import "fmt" /* * This is the usual recursive quicksort function. It sorts a slice. */ func qsort(data []int) { // This is the usual array split algorithm for quicksort. It // returns two slices for the two partitions. This function is // created as a dynamic function. I don't know why go does not // allow the more usual notation. split := func(data [] int) ([]int, []int) { pivot := data[0] // Mid value for splitting. left := 1 // Left (lesser side) scanner. right := len(data) - 1 // Right (greater side) scanner. // Repeat until the data is partitioned. for left <= right { // Move the left until we find a large one. for left < len(data) && data[left] <= pivot{ left++ } // Move the right until we find a small one. for data[right] > pivot { right-- } // If they have not passed each other, swap and // go on. if left < right { data[left], data[right] = data[right], data[left] } } // Put the pivot in place and return the partitions. data[0], data[right] = data[right], data[0] return data[0:right], data[right+1:] } // If there is more than one, split 'em and sort 'em. if len(data) > 1 { smaller, larger := split(data) qsort(smaller) qsort(larger) } } func main() { // Read any number of integers, hoping Go manages to do this // efficiently. This creates an array of 20 and returns an empty // slice. But the append() will substitute a larger array if needed. fmt.Println("Enter numbers:") values := make([]int,0,20) for { var val int num, _ := fmt.Scan(&val) if num == 1 { values = append(values, val) } else { break } } // Dump the entered values. for _,v := range(values) { fmt.Print(v," ") } fmt.Println() // Perform the quicksort qsort(values) // So what do they look like now? fmt.Println() for _,v := range(values) { fmt.Print(v," ") } fmt.Println() }