码迷,mamicode.com
首页 > 其他好文 > 详细

Golang(笔记) 顺序编程

时间:2014-05-28 20:32:20      阅读:306      评论:0      收藏:0      [点我收藏+]

标签:style   c   class   blog   code   java   

bubuko.com,布布扣
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)
    }
}
bubuko.com,布布扣

 

Golang(笔记) 顺序编程,布布扣,bubuko.com

Golang(笔记) 顺序编程

标签:style   c   class   blog   code   java   

原文地址:http://www.cnblogs.com/yahue/p/3754792.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!