Go R1 Day 20
tech development 100DaysOfCode golang microblog puzzles algorithms
Day 20 of 100
progress
Hackerrank challenge “Bubble Sort”
Code
package algos
import (
"fmt"
"sort"
)
// My submission: https://www.hackerrank.com/challenges/ctci-bubble-sort/submissions/code/193046709
// Complete the countSwaps function below.
func countSwaps(list []int) {
s := len(list)
swapCounter := 0
// for each iterate through to do one complete sort for each
for ipc := 0; ipc < s; ipc++ {
// iterate by moving this single item to the end and rinse and repeat with loop above this
for i := 0; i < s-1; i++ {
this := list[i]
next := list[i+1]
if this > next {
list[i+1] = this
list[i] = next // switch places
swapCounter++
}
}
}
//return int(swapCounter)
fmt.Printf("Array is sorted in %d swaps.\n", swapCounter)
fmt.Printf("First Element: %v\n", list[0])
fmt.Printf("Last Element: %v\n", list[len(list)-1])
}