GO语言练习:第一个Go语言工程--排序

简介:

1、代码框架 /home/fengbo/sorter

复制代码
$ tree
.
├── bin
├── pkg
├── readme.txt
└── src
    ├── algorithms
    │   ├── bubblesort
    │   │   ├── bubblesort.go
    │   │   └── bubblesort_test.go
    │   └── qsort
    │       ├── qsort.go
    │       └── qsort_test.go
    └── sorter
        └── sorter.go
复制代码

  1.1、src/algorithms/bubblesort/bubblesort.go

复制代码
//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;
                        }
                }
        }
}
复制代码

  1.2、src/algorithms/bubblesort/bubblesort_test.go

复制代码
//bubble_test.ho
package bubblesort

import "testing"

func TestBubbleSort1(t * testing.T) {
        values := []int {5, 4, 3, 2, 1}
        BubbleSort(values)
        for i := 0; i < len(values) - 1; i++ {
                if values[i] > values[i + 1] {
                        t.Error("ubbleSort() faild. Got at ", values[i], values[i + 1])
                        break
                }
        }
}

func TestBubbleSort2(t * testing.T) {
        values := []int{5}
        BubbleSort(values)
        if(values[0] != 5) {
                t.Error("BubbleSort() faild. Got ", values, "Excepted 5")
        }
}
复制代码

  1.3、src/algorithms/qsort/qsort.go

复制代码
//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)
}
复制代码

  1.4、src/algorithms/qsort/qsort_test.go

复制代码
//qsort_test.go
package qsort

import "testing"

func TestQuickSort1(t * testing.T) {
        values := []int {5, 4, 3, 2, 1}
        QuickSort(values)
        var i int;
        var j int = len(values) - 1
        for i = 0; i < j; i++ {
                if values[i] > values[i + 1] {
                        t.Error("QuickSort() faild")
                        break;
                }
        }
}

func TestQuickSort2(t * testing.T) {
        values := []int {5}
        QuickSort(values)
        if values[0] != 5 {
                t.Error("QuickSort() faild. Got", values);
        }
}
复制代码

  1.5、src/sorter/sorter.go

复制代码
package main

import "bufio"
import "flag"
import "fmt"
import "io"
import "os"
import "strconv"
import "time"

import "algorithms/bubblesort"
import "algorithms/qsort"

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)

                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("Faild to create the outfile ", 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("Sorting algorithm", * algorithm, "is either unknown or ensupported.")
                }
                t2 := time.Now()

                fmt.Println("The sorting process costs", t2.Sub(t1), "to complete.")
                writeValues(values, * outfile)
        }else {
                fmt.Println(err)
        }
}
复制代码

2、编译

  2.1、设置环境变量

[fengbo@sorter]$ pwd
/home/fengbo/sorter
[fengbo@sorter]$ export GOPATH="/home/fengbo/sorter"

  2.1编译级安装

复制代码
$ go build algorithms/bubblesort
$ go build algorithms/qsort
$ go install algorithms/bubblesort
$ go install algorithms/qsort
$ go build sorter
复制代码

  2.2、编译及安装后的目录结构

复制代码
$ tree
.
├── bin
├── pkg
│   └── linux_386
│       └── algorithms
│           ├── bubblesort.a
│           └── qsort.a
├── readme.txt
├── sorter
└── src
    ├── algorithms
    │   ├── bubblesort
    │   │   ├── bubblesort.go
    │   │   └── bubblesort_test.go
    │   └── qsort
    │       ├── qsort.go
    │       └── qsort_test.go
    └── sorter
        └── sorter.go
复制代码

 


3、运行

  3.1、未排序的文本文件

复制代码
$ cat unsorted.dat
6
345
76564
5
66
443654
757
2365
565
复制代码

  3.2、运行排序程序

$ ./sorter -i unsorted.dat -o sorted.dat -a qsort
infile = unsorted.dat outfile =  sorted.dat algorithm =  qsort
The sorting process costs 2.22us to complete.

  3.3、排序后的结果文件

复制代码
$ ls
sorted.dat  sorter unsorted.dat
$ cat sorted.dat
5
6
66
345
565
757
2365
76564
443654
复制代码

4、注释

  代码来源于《Go语言编程》一书的第二章,目录结构与原书有些差异。

 


本文转自郝峰波博客园博客,原文链接:http://www.cnblogs.com/fengbohello/p/4620644.html,如需转载请自行联系原作者


相关文章
|
15天前
|
Go
go语言中的数据类型
go语言中的数据类型
13 0
|
5天前
|
关系型数据库 Go API
《Go 简易速速上手小册》第1章:Go 语言基础(2024 最新版)(上)
《Go 简易速速上手小册》第1章:Go 语言基础(2024 最新版)(上)
31 1
|
2天前
|
数据采集 存储 Go
使用Go语言和chromedp库下载Instagram图片:简易指南
Go语言爬虫示例使用chromedp库下载Instagram图片,关键步骤包括设置代理IP、创建带代理的浏览器上下文及执行任务,如导航至用户页面、截图并存储图片。代码中新增`analyzeAndStoreImage`函数对图片进行分析和分类后存储。注意Instagram的反爬策略可能需要代码适时调整。
使用Go语言和chromedp库下载Instagram图片:简易指南
|
21天前
|
存储 安全 Go
掌握Go语言:Go语言类型转换,无缝处理数据类型、接口和自定义类型的转换细节解析(29)
掌握Go语言:Go语言类型转换,无缝处理数据类型、接口和自定义类型的转换细节解析(29)
|
1天前
|
程序员 Go API
【Go语言快速上手(二)】 分支与循环&函数讲解
【Go语言快速上手(二)】 分支与循环&函数讲解
|
1天前
|
Go
Golang深入浅出之-Go语言基础语法:变量声明与赋值
【4月更文挑战第20天】本文介绍了Go语言中变量声明与赋值的基础知识,包括使用`var`关键字和简短声明`:=`的方式,以及多变量声明与赋值。强调了变量作用域、遮蔽、初始化与零值的重要性,并提醒读者注意类型推断时的一致性。了解这些概念有助于避免常见错误,提高编程技能和面试表现。
15 0
|
1天前
|
编译器 Go 开发者
Go语言入门|包、关键字和标识符
Go语言入门|包、关键字和标识符
14 0
|
5天前
|
API Go
使用Go语言通过API获取代理IP并使用获取到的代理IP
使用Go语言通过API获取代理IP并使用获取到的代理IP
|
6天前
|
前端开发 Java Go
开发语言详解(python、java、Go(Golong)。。。。)
开发语言详解(python、java、Go(Golong)。。。。)
|
15天前
|
存储 Java 编译器
go语言基础语法
go语言基础语法