From 89b7afb0cf19eaec4b4e74a7b9863a2a20b0e34c Mon Sep 17 00:00:00 2001 From: UnleashMe69 <57689207+UnleashMe69@users.noreply.github.com> Date: Sat, 27 Mar 2021 18:15:52 +0100 Subject: [PATCH] bubble-sort.go added (#117) * bubble-sort.go added * Updated bubble sort algorithm --- sorting/README.md | 2 ++ sorting/go/bubble-sort.go | 28 ++++++++++++++++++++++++++++ 2 files changed, 30 insertions(+) create mode 100644 sorting/go/bubble-sort.go diff --git a/sorting/README.md b/sorting/README.md index 7cbff5e7d..8ab3d1787 100644 --- a/sorting/README.md +++ b/sorting/README.md @@ -47,3 +47,5 @@ ### Golang 1. [Insertion Sort](go/insertion-sort.go) 2. [Quick Sort](go/quick-sort.go) +3. [Bubble Sort](go/bubble-sort.go) + diff --git a/sorting/go/bubble-sort.go b/sorting/go/bubble-sort.go new file mode 100644 index 000000000..43135763c --- /dev/null +++ b/sorting/go/bubble-sort.go @@ -0,0 +1,28 @@ +/* + Bubble sort is a recursive algorithm based on swapping 2 values closest to each other: k and k+1 + We start by checking the first two values of the array, and we swap them if the first value is bigger than the second one. + Then we recursively swap the second value with the third, if needed and so on until the array is sorted. + Average Time Complexity: O(n^2)) +*/ + +package main + +import ( + "fmt" +) + +func bubbleSort(sliceInt []int, n int) { + for k := 0; k < n-1; k++ { + if sliceInt[k] > sliceInt[k+1] { + // We swaps the value if sliceInt[k] > sliceInt[k+1] + sliceInt[k], sliceInt[k+1] = sliceInt[k+1], sliceInt[k] + bubbleSort(sliceInt, n) + } + } +} + +func main() { + sliceInt := []int{1, 2, -1, 0, 534, -100, 9, 53, 203} + bubbleSort(sliceInt, len(sliceInt)) + fmt.Println(sliceInt) +}