Skip to content

Instantly share code, notes, and snippets.

@antsmartian
Created February 3, 2012 13:30
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 antsmartian/1730189 to your computer and use it in GitHub Desktop.
Save antsmartian/1730189 to your computer and use it in GitHub Desktop.
Bubble Sort alg in Groovy!
//change this array and play with Bubble Sort!
a = [1,43,5,67,8,912,3,465,89,89,82,34]
println a.size()
for(out in (a.size()-2)..2)
{
0.upto(out) { index ->
if(a[index] > a[index+1])
swap(index,index+1)
}
}
def swap(def one,def two)
{
def temp = a[one]
a[one] = a[two]
a[two] = temp
}
a = [2,34,4,123,45,56,3,56,67,87,21,45,56,67,22,4234,4234,2342,1,34,546,67,677,343,4,41,32,456,1341,13,454,234,453,565,5,524,234,234,5456,567,673,245,567,78,78,324,56576,782,435,676,873,2,345,6767,7,3463,3,6767673,34534,2,345,656,3,5652,1,34345,3453545,35345356,66,7883345,676787,8988]
b = a
long startTime = System.currentTimeMillis();
for(out in (a.size()-2)..2)
{
0.upto(out) { index ->
if(a[index] > a[index+1])
{
use(Collections) {
a.swap(index,index+1)
}
}
}
}
long endTime = System.currentTimeMillis();
println "The bubble sort have taken ${endTime-startTime} seconds to finish sorting for ${a.size()} elements \n \n"
println a
//test cases... these are passing!! Yipeee :D
assert b.sort() == a
assert b.size() == a.size()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment