首页 > 代码库 > Golang(笔记) 顺序编程
Golang(笔记) 顺序编程
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) } }
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。