Skip to content

Instantly share code, notes, and snippets.

@ndkhoa
Created February 27, 2019 02:16
Show Gist options
  • Select an option

  • Save ndkhoa/06bf474bd38942870a33843c25c8a43b to your computer and use it in GitHub Desktop.

Select an option

Save ndkhoa/06bf474bd38942870a33843c25c8a43b to your computer and use it in GitHub Desktop.
Bubble Sort
package main
import "fmt"
func BubbleSort(array []int) []int {
endIndex := len(array)
var flag, counter int
// Cach 1
// counter = 0
// for i := 0; i < endIndex; i++ {
// for j := 1; j < endIndex-i; j++ {
// counter++
// if array[j-1] > array[j] {
// array[j-1], array[j] = array[j], array[j-1]
// }
// }
// }
// Cach 2
for i := 0; i < endIndex; i++ {
flag = 0
for j := 1; j < endIndex-i; j++ {
counter++
if array[j-1] > array[j] {
array[j-1], array[j] = array[j], array[j-1]
flag = 1
}
}
if flag == 0 {
break
}
}
fmt.Printf("counter: %v\n", counter)
fmt.Println(array)
return array
}
func main() {
BubbleSort([]int{5, 1, 4, 2, 8})
fmt.Println()
BubbleSort([]int{5, 1, 4, 7, 8})
fmt.Println()
BubbleSort([]int{1, 2, 3, 4, 5})
}
def bubble_sort(array)
counter = 0
for index in 0...array.size
puts array[index]
end
# puts "counter: #{counter}"
# puts array.join(' ')
end
bubble_sort([5, 1, 4, 2, 8])
puts
bubble_sort([5, 1, 4, 7, 8])
puts
bubble_sort([1, 2, 3, 4, 5])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment