forked from CodersForLife/Data-Structures-Algorithms
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathquicksort.go
More file actions
54 lines (42 loc) · 1.12 KB
/
Copy pathquicksort.go
File metadata and controls
54 lines (42 loc) · 1.12 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
// Quick Sort in Go (Golang)
package main
import (
"fmt"
"math/rand"
"time"
)
//main function
func main() {
slice := generateSlice(15) //number of random numbers you want to be generated
fmt.Println("\nUnsorted\n", slice)
quicksort(slice)
fmt.Println("\nSorted\n", slice, "\n")
}
// Generates a slice of random numbers of size specified at line 12
func generateSlice(size int) []int {
slice := make([]int, size, size)
rand.Seed(time.Now().UnixNano())
for i := 0; i < size; i++ {
slice[i] = rand.Intn(999) - rand.Intn(999)
}
return slice
}
//quick sort function
func quicksort(a []int) []int {
if len(a) < 2 {
return a
}
left, right := 0, len(a)-1
pivot := rand.Int() % len(a)
a[pivot], a[right] = a[right], a[pivot]
for i, _ := range a {
if a[i] < a[right] {
a[left], a[i] = a[i], a[left]
left++
}
}
a[left], a[right] = a[right], a[left]
quicksort(a[:left])
quicksort(a[left+1:])
return a
}