forked from MakeContributions/DSA
-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
bubble-sort.go added (MakeContributions#117)
* bubble-sort.go added * Updated bubble sort algorithm
- Loading branch information
UnleashMe69
authored
Mar 27, 2021
1 parent
aa91912
commit 89b7afb
Showing
2 changed files
with
30 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
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,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) | ||
} |