项目结构
冒泡排序算法,源文件bubblesort.go
package bubblesort
// 冒泡排序
func BubbleSort(values []int) {
for i := 0; i < len(values) - 1; i ++ {
flag := true
for j := 0; j < len(values) - i - 1; i ++ {
if values[j] > values[j + 1] {
values[j], values[j + 1] = values[j + 1], values[j]
flag = false
}
if flag == true {
break
}
}
}
}
快速排序算法,源文件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)
}
主文件main.go
package main
import (
"flag"
"os"
"bufio"
"io"
"strconv"
"time"
"sorter/algorithms/qsort"
"sorter/algorithms/bubblesort"
"fmt"
)
var infile *string = flag.String("i","unsorted.dat","File contains values of 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 {
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 {
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 {
println("Failed to create the ouput 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 {
println("infile =", *infile,"outfile=", *outfile, "algorithm =", *algorithm)
}
values, err := readValues(*infile)
if err == nil {
fmt.Println("Read values:%v", values)
if err == nil {
t1 := time.Now()
switch *algorithm {
case "qsort":
qsort.QuickSort(values)
case "bubblesort":
bubblesort.BubbleSort(values)
default:
println("Sorting algorithm", *algorithm, "is either unknown or unsupported.")
}
t2 := time.Now()
println("The sorting process conts", t2.Sub(t1), "to complete.")
writeValues(values, *outfile)
}
}else{
println(err)
}
}
排序结果