Skip to content

Instantly share code, notes, and snippets.

@antsmartian
Created February 4, 2012 15:46
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/1738571 to your computer and use it in GitHub Desktop.
Save antsmartian/1738571 to your computer and use it in GitHub Desktop.
Insertion Sort In Groovy
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();
(1..(a.size()-2)).each { out ->
def temp = a.getAt(out)
def index = out
while(index>0 && a.getAt(index-1) >= temp)
{
value = a.getAt(index-1)
a.putAt(index,value)
--index
}
a.putAt(index,temp)
}
long endTime = System.currentTimeMillis();
println "The insertion 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()
@ChrisWW
Copy link

ChrisWW commented Dec 10, 2021

IMO 4 line for:
(1..(a.size()-1)).each { out ->

the last element is not triggered

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment