-
Notifications
You must be signed in to change notification settings - Fork 22
Expand file tree
/
Copy pathBubbleSort.go
More file actions
46 lines (40 loc) · 887 Bytes
/
Copy pathBubbleSort.go
File metadata and controls
46 lines (40 loc) · 887 Bytes
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
package main
import (
"fmt"
"math/rand"
"time"
)
func main() {
slice := generateSlice(20)
fmt.Println("\n--- Unsorted --- \n\n", slice)
bubblesort(slice)
fmt.Println("\n--- Sorted ---\n\n", slice, "\n")
}
// Generates a slice of size, size filled with random numbers
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
}
func bubblesort(items []int) {
var (
n = len(items)
sorted = false
)
for !sorted {
swapped := false
for i := 0; i < n-1; i++ {
if items[i] > items[i+1] {
items[i+1], items[i] = items[i], items[i+1]
swapped = true
}
}
if !swapped {
sorted = true
}
n = n - 1
}
}