标签:style c class blog code java
package main import ( "fmt" "bufio" "io" "os" "strconv" "flag" ) var infile *string=flag.String("i","unsorted.data","File contains values for sorting") var outfile *string=flag.String("o","sorted.data","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)//转换字符数组为字符串 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 outout file ",outfile) return err } defer file.Close() for _,value:=range values{ str:=strconv.Itoa(value) file.WriteString(str+"\n") } return nil } //冒泡排序法 func BubbleSort(values []int) []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 } } return values; } func main() { flag.Parse() if infile!=nil{ fmt.Println("infile=",*infile," outfile=",*outfile," algorithm=",*algorithm) } values,err:=readValues(*infile) if(err==nil){ fmt.Println("read values:",values) values=BubbleSort(values) errout:= writeValues(values,*outfile) if errout!=nil{ fmt.Println(errout) } } else{ fmt.Println(err) } }
Golang(笔记) 顺序编程,布布扣,bubuko.com
标签:style c class blog code java
原文地址:http://www.cnblogs.com/yahue/p/3754792.html