Go language exercise: First go language Project--sort

Source: Internet
Author: User

1. Code

2. Compiling

3. Operation

1. Code Frame/home/fengbo/sorter

$ tree.├──bin├──pkg├──readme.txt└──src    ├──algorithms    │├──bubblesort    ││├──bubblesort.go    │ │└──bubblesort_test.go    │└──qsort    │     ├──qsort.go    │     └──qsort_test.go    └──sorter< C16/>└──sorter.go

1.1, Src/algorithms/bubblesort/bubblesort.go

//Bubblesort.go Packagebubblesortfunc Bubblesort (values []int) {flag:=true         forI: = 0; I < Len (values)-1; i++{flag=true                 forJ: = 0; J < Len (values)-i-1; J + + {                        ifVALUES[J] > values[j + 1] {values[j], values[j+ 1] = values[j + 1], VALUES[J] Flag=false                        }                        ifFlag = =true {                                 Break; }                }        }}

1.2, Src/algorithms/bubblesort/bubblesort_test.go

//Bubble_test.ho PackageBubblesortImport"Testing"func TestBubbleSort1 (t*testing. T) {values:= []int{5, 4, 3, 2, 1} bubblesort (values) forI: = 0; I < Len (values)-1; i++ {                ifValues[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 Packageqsortfunc QuickSort (values []int, left, rightint) {temp:=Values[left] P:=Left I, J:=Left , right forI <=J { forJ >= P && Values[j] >=Temp {J--                }                ifJ >=p {values[p]=Values[j] P=J}ifValues[i] <= temp && i <=p {i++                }                ifI <=p {values[p]=Values[i] P=i}} Values[p]=TempifP-left > 1{QuickSort (values, left, p-1)        }        ifRight-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 PackageqsortImport"Testing"func TestQuickSort1 (t*testing. T) {values:= []int{5, 4, 3, 2, 1} QuickSort (values) var iint; var Jint= Len (values)-1 fori = 0; I < J; i++ {                ifValues[i] > values[i + 1] {t.error ("QuickSort () faild")                         Break; }}}func TestQuickSort2 (t*testing. T) {values:= []int{5} QuickSort (values)ifVALUES[0]! = 5{t.error ("QuickSort () faild. Got ", values); }}

1.5, Src/sorter/sorter.go

 PackageMainImport"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)ifErr! =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 ()ifErr1! =nil{ifErr1! =io. eof{Err=ERR1} Break                }                ifIsprefix {fmt. Println ("A too long line, seems unexpected.")                        return} STR:=string (line) value, ERR1:=StrConv. Atoi (str)ifErr1! =nil{Err=err1return} values=Append (values, value)}return}func writevalues (values []int, outfile String) error {file, err:=OS. Create (outfile)ifErr! =Nil {fmt. Println ("Faild to create the outfile", outfile)returnErr} defer file. Close () for_, Value: =range Values {str:=StrConv. Itoa (value) file. WriteString (str+ "\ n")        }        returnNil}func Main () {flag. Parse ()ifInFile! =Nil {fmt. Println ("infile =", *infile, "outfile =", *outfile, "algorithm =", *algorithm)} Values, err:= Readvalues (*infile)ifErr = =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. Compiling

2.1. Setting Environment variables

[email protected]]$ pwd/home/fengbo/export gopath= "/home/fengbo/sorter"

2.1 Compile-level installation

$ go Build algorithms/bubblesort$ Go build algorithms/qsort$ Go install algorithms/bubblesort$ go I Nstall algorithms/qsort$ go build sorter

2.2. Compilation and post-installation directory structure

linux_386│     └──algorithms│         ├──bubblesort.a│         sorter└──src    ├──algorithms    │ ├──bubblesort    ││├──bubblesort.go    ││└──bubblesort_test.go    │└──qsort    │     ├──qsort . Go    │     └──qsort_test.go    └──sorter        └──sorter.go

3. Operation

3.1. unsorted text File

$ cat Unsorted.dat6345765645664436547572365565

3.2. Run the Sequencing program

$./sorter-i unsorted.dat-o Sorted.dat-= unsorted.dat outfile =  Sorted.dat algorithm =  2.22u s to complete.

3.3. Sorted result File

$ lssorted.dat  sorter unsorted.dat$ cat Sorted.dat5666345565757236576564443654

4. Comments

The code comes from the second chapter of the book "Go Language Programming", where the directory structure differs from the original book.

Go language exercise: First go language Project--sort

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.