From 2d7e5ef31d1050b6b7c2397a157f4c0f554b0110 Mon Sep 17 00:00:00 2001 From: ashishkrishan1995 Date: Sun, 7 Oct 2018 02:56:19 +0530 Subject: [PATCH 1/2] selection sort in golang --- .../Selection Sort/golang/selectionSort.go | 40 +++++++++++++++++++ 1 file changed, 40 insertions(+) create mode 100644 Sorting/Selection Sort/golang/selectionSort.go diff --git a/Sorting/Selection Sort/golang/selectionSort.go b/Sorting/Selection Sort/golang/selectionSort.go new file mode 100644 index 000000000..80dc05e6e --- /dev/null +++ b/Sorting/Selection Sort/golang/selectionSort.go @@ -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] + } +} \ No newline at end of file From 755be61bc9442b2d991d371bbe6e523034a8d55f Mon Sep 17 00:00:00 2001 From: ashishkrishan1995 Date: Sun, 7 Oct 2018 02:59:29 +0530 Subject: [PATCH 2/2] added bubblesort in golang --- Sorting/bubbleSort/golang/bubbleSort.go | 32 +++++++++++++++++++++++++ 1 file changed, 32 insertions(+) create mode 100644 Sorting/bubbleSort/golang/bubbleSort.go diff --git a/Sorting/bubbleSort/golang/bubbleSort.go b/Sorting/bubbleSort/golang/bubbleSort.go new file mode 100644 index 000000000..d259c896c --- /dev/null +++ b/Sorting/bubbleSort/golang/bubbleSort.go @@ -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) + +} \ No newline at end of file