package main
import "fmt"
/*
* The append method can be used with an anonymous array to effectively
* create a variable-sized array. Simply make your slice, and keep
* appending.
*/
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([]float32,0,20)
for {
var val float32
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()
// Bubble sort. Outer loop operates in a slice that starts
// as the whole array, and shrinks from the right.
unsorted := values[:]
for swapped := true;
swapped && len(unsorted) > 1;
unsorted = unsorted[0:len(unsorted)-1] {
// Inner scan bubbles pairs to the end of the outer
// slice.
pair := unsorted[0:2]
swapped = false
for true {
// If the pair is out of order, swap it.
if pair[0] > pair[1] {
pair[0], pair[1] = pair[1], pair[0]
swapped = true
}
// See if we've covered the outer slice. This
// somewhat hackerly test checks if the two slices
// have the same end by seeing if they have the same
// unused capacity.
if cap(unsorted) - len(unsorted) ==
cap(pair) - len(pair) {
break
}
// Move on. Note: This is after the break so
// we don't advance the slice after its last
// use. We don't need to change it since
// we're done, and it will go out-of-bounds if
// the capacity happens to exactly equal the
// unsorted slice size.
pair = pair[1:3]
}
}
// So what do they look like now?
fmt.Println()
for _,v := range(values) {
fmt.Print(v," ")
}
fmt.Println()
}