File tree Expand file tree Collapse file tree 1 file changed +54
-0
lines changed
Expand file tree Collapse file tree 1 file changed +54
-0
lines changed Original file line number Diff line number Diff line change 1+ // Quick Sort in Go (Golang)
2+ package main
3+
4+ import (
5+ "fmt"
6+ "math/rand"
7+ "time"
8+ )
9+ //main function
10+ func main () {
11+
12+ slice := generateSlice (15 ) //number of random numbers you want to be generated
13+ fmt .Println ("\n Unsorted\n " , slice )
14+ quicksort (slice )
15+ fmt .Println ("\n Sorted\n " , slice , "\n " )
16+ }
17+
18+ // Generates a slice of random numbers of size specified at line 12
19+ func generateSlice (size int ) []int {
20+
21+ slice := make ([]int , size , size )
22+ rand .Seed (time .Now ().UnixNano ())
23+ for i := 0 ; i < size ; i ++ {
24+ slice [i ] = rand .Intn (999 ) - rand .Intn (999 )
25+ }
26+ return slice
27+ }
28+
29+ //quick sort function
30+ func quicksort (a []int ) []int {
31+ if len (a ) < 2 {
32+ return a
33+ }
34+
35+ left , right := 0 , len (a )- 1
36+
37+ pivot := rand .Int () % len (a )
38+
39+ a [pivot ], a [right ] = a [right ], a [pivot ]
40+
41+ for i , _ := range a {
42+ if a [i ] < a [right ] {
43+ a [left ], a [i ] = a [i ], a [left ]
44+ left ++
45+ }
46+ }
47+
48+ a [left ], a [right ] = a [right ], a [left ]
49+
50+ quicksort (a [:left ])
51+ quicksort (a [left + 1 :])
52+
53+ return a
54+ }
You can’t perform that action at this time.
0 commit comments