Skip to content

Commit

Permalink
selection sort in golang
Browse files Browse the repository at this point in the history
  • Loading branch information
ashishkrishan1995 committed Oct 6, 2018
1 parent e5da508 commit 2d7e5ef
Showing 1 changed file with 40 additions and 0 deletions.
40 changes: 40 additions & 0 deletions Sorting/Selection Sort/golang/selectionSort.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
// Selection Sort in Golang
package main

import (
"fmt"
"math/rand"
"time"
)

func main() {

slice := generateSlice(20)
fmt.Println("\n--- Unsorted --- \n\n", slice)
selectionsort(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 selectionsort(items []int) {
var n = len(items)
for i := 0; i < n; i++ {
var minIdx = i
for j := i; j < n; j++ {
if items[j] < items[minIdx] {
minIdx = j
}
}
items[i], items[minIdx] = items[minIdx], items[i]
}
}

0 comments on commit 2d7e5ef

Please sign in to comment.