用于实现快速排序和冒泡排序的东东。
包括了蛮多东西的实现,输入输出,字符串处理等。。。。
bubblesort.go
package bubblesort func BubbleSort(values []int) { flag := true for i := 0; i < len(values)-1; i++ { flag = true for j := 0; j < len(values)-i-1; j++ { if values[j] > values[j+1] { values[j], values[j+1] = values[j+1], values[j] flag = false } } if flag == true { break } } }
qsort.go
package qsort func quickSort(values []int, left, right int) { temp := values[left] p := left i, j := left, right for i <= j { for j >= p && values[j] >= temp { j-- } if j >= p { values[p] = values[j] p = j } if values[i] <= temp && i <= p { i++ } if i <= p { values[p] = values[i] p = i } } values[p] = temp if p-left > 1 { quickSort(values, left, p-1) } if right-p > 1 { quickSort(values, p+1, right) } } func QuickSort(values []int) { quickSort(values, 0, len(values)-1) }
qsort_test.go
package qsort import ( "testing" ) func TestQuickSort1(t *testing.T) { values := []int{5, 4, 3, 2, 1} QuickSort(values) if values[0] != 1 || values[1] != 2 || values[2] != 3 || values[3] != 4 || values[4] != 5 { t.Error("QuickSort() failed .Got", values, "Expected 1 2 3 4 5") } }
sorter.go
package main import ( "bufio" "flag" "fmt" "helloworld/algorithms/bubblesort" "helloworld/algorithms/qsort" "io" "os" "strconv" "time" ) var infile *string = flag.String("i", "infile", "File contains values for sorting") var outfile *string = flag.String("o", "outfile", "File to receive sorted values") var algorithm *string = flag.String("a", "qsort", "Sort algorithm") func readValues(infile string) (values []int, err error) { file, err := os.Open(infile) if err != nil { fmt.Println("Failed to open input file ", infile) return } defer file.Close() br := bufio.NewReader(file) values = make([]int, 0) for { line, isPrefix, err1 := br.ReadLine() if err1 != nil { if err1 != io.EOF { err = err1 } break } if isPrefix { fmt.Println("A too long line, seems unexpected.") return } str := string(line) value, err1 := strconv.Atoi(str) if err1 != nil { err = err1 return } values = append(values, value) } return } func writeValues(values []int, outfile string) error { file, err := os.Create(outfile) if err != nil { fmt.Println("Failed to create the output file ", outfile) return err } defer file.Close() for _, value := range values { str := strconv.Itoa(value) file.WriteString(str + "\n") } return nil } func main() { flag.Parse() if infile != nil { fmt.Println("infile = ", *infile, " outfile = ", *outfile, " algorithm = ", *algorithm) } values, err := readValues(*infile) if err == nil { t1 := time.Now() switch *algorithm { case "qsort": qsort.QuickSort(values) case "bubblesort": bubblesort.BubbleSort(values) default: fmt.Println("algorithm is unknows or un supported.") } t2 := time.Now() fmt.Println("The sorting process costs ", t2.Sub(t1), " to complete.") writeValues(values, *outfile) } else { fmt.Println(err) } }