-
Notifications
You must be signed in to change notification settings - Fork 1k
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Merge pull request #166 from ashishkrishan1995/master
selection sort in golang
- Loading branch information
Showing
2 changed files
with
72 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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] | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,32 @@ | ||
package main | ||
|
||
import ( | ||
"fmt" | ||
) | ||
|
||
var toBeSorted [10]int = [10]int{1,3,2,4,8,6,7,2,3,0} | ||
|
||
func bubbleSort(input [10]int) { | ||
// n is the number of items in our list | ||
n := 10 | ||
swapped := true | ||
for swapped { | ||
swapped = false | ||
for i := 1; i < n-1; i++ { | ||
if input[i-1] > input[i] { | ||
fmt.Println("Swapping") | ||
// swap values using Go's tuple assignment | ||
input[i], input[i-1] = input[i-1], input[i] | ||
swapped = true | ||
} | ||
} | ||
} | ||
fmt.Println(input) | ||
} | ||
|
||
|
||
func main() { | ||
fmt.Println("Hello World") | ||
bubbleSort(toBeSorted) | ||
|
||
} |