Skip to content

Instantly share code, notes, and snippets.

@sporto
Last active December 22, 2015 06:38
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sporto/6432229 to your computer and use it in GitHub Desktop.
Save sporto/6432229 to your computer and use it in GitHub Desktop.
Bubble sort
package main
import (
"fmt"
)
func bubble(s []int) {
for i := len(s) - 2; i >= 0; i-- {
for j := 0; j <= i; j++ {
if s[j] > s[j+1] {
s[j], s[j+1] = s[j+1], s[j]
}
}
}
}
func main() {
arr := []int{2, 10, 1, 9, 5, 6, 8, 3, 7, 4}
bubble(arr)
fmt.Println(arr)
}
function bubble(a) {
var swapped;
do {
swapped = false;
for(var i = 0; i < a.length - 1; i++) {
if(a[i] > a[i + 1]) {
var temp = a[i];
a[i] = a[i + 1];
a[i + 1] = temp;
swapped = true;
}
}
} while (swapped);
}
module.exports = bubble;
require "benchmark"
bubble = ->(list) do
return list if list.size <= 1 # already sorted
swapped = true
while swapped do
swapped = false
0.upto(list.size-2) do |i|
if list[i] > list[i+1]
list[i], list[i+1] = list[i+1], list[i] # swap values
swapped = true
end
end
end
list
end
puts bubble.call([2, 10, 1, 9, 5, 6, 8, 3, 7, 4])
time = Benchmark.bm(500) do |x|
x.report(:bubble) { bubble.call([2, 10, 1, 9, 5, 6, 8, 3, 7, 4]) }
end
puts time
package main
import (
"testing" //import go package for testing related functionality
)
func Benchmark_bubble(b *testing.B) { //benchmark function starts with "Benchmark" and takes a pointer to type testing.B
for i := 0; i < b.N; i++ {
arr := []int{2, 10, 1, 9, 5, 6, 8, 3, 7, 4}
bubble(arr)
}
}
// go test -file bubble_test.go -bench=".*"
var Benchmark = require('benchmark');
var bubble = require('./bubble');
var suite = new Benchmark.Suite;
suite
.add('bubble', function() {
var a = [2, 10, 1, 9, 5, 6, 8, 3, 7, 4];
bubble(a);
})
// add listeners
.on('cycle', function(event) {
console.log(String(event.target));
})
// .on('complete', function() {
// console.log('Fastest is ' + this.filter('fastest').pluck('name'));
// })
.run({'async': false});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment