Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit 4be1846

Browse files
Quick Sort Algorithm in Golang
1 parent 1f9fb6d commit 4be1846

File tree

1 file changed

+54
-0
lines changed

1 file changed

+54
-0
lines changed

‎Sorting/quicksort.go

Lines changed: 54 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,54 @@
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("\nUnsorted\n", slice)
14+
quicksort(slice)
15+
fmt.Println("\nSorted\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+
}

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /