Skip to content

Commit

Permalink
Merge pull request #1 from magnoom/magnoom-patch-1
Browse files Browse the repository at this point in the history
Create bubblesort.go
  • Loading branch information
dxeon authored Oct 16, 2020
2 parents baa7237 + e679ea8 commit 0e19df3
Showing 1 changed file with 47 additions and 0 deletions.
47 changes: 47 additions & 0 deletions Sorting Algorithm/bubblesort.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
// Bubble Sort in Golang
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
}
}

0 comments on commit 0e19df3

Please sign in to comment.