go樣本1:檔案讀寫和排序(快速 冒泡)

來源:互聯網
上載者:User


package mainimport ("algorithm/bubblesort""algorithm/qsort""bufio""flag""fmt""io""os""strconv""time")var infile *string = flag.String("i", "unsorted.dat", "File contains values for sorting")var outfile *string = flag.String("o", "sorted.dat", "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 the 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)fmt.Print(str, " ")value, err1 := strconv.Atoi(str)if err1 != nil {err = err1return}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 {fmt.Println(err)} else {t1 := time.Now()switch *algorithm {case "qsort":qsort.QuickSort(values)case "bubblesort":bubblesort.BubbleSort(values)default:fmt.Println("Sorting algorithm", *algorithm, "is either unknown or unsupported.")}t2 := time.Now()fmt.Println("The sorting process costs", t2.Sub(t1), "to complete.")writeValues(values, *outfile)}}
package bubblesortfunc BubbleSort(values []int) {for i := 0; i < len(values)-1; i++ {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]}}}}

package qsortfunc quickSort(values []int, left, right int) {temp := values[left]p := lefti, j := left, rightfor 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  //provKeyif 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)}





相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.