Created
November 8, 2011 03:59
-
-
Save rrgroovy/1346960 to your computer and use it in GitHub Desktop.
Reinvention of the Wheel Series, "Bubble Sort in Groovy".
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class BubbleSort { | |
def list | |
def sort() { | |
def eachPairIndex = { Collection l -> | |
def range = 0..<l.size() | |
[range, range.tail()].transpose() | |
} | |
while (! eachPairIndex(this.list).inject(true) { rslt, idx -> | |
if (! (this.list[idx[0]] < this.list[idx[1]]) ) { | |
use(Collections){ this.list.swap(idx[0], idx[1]) } | |
rslt &= false | |
} else rslt | |
} ); | |
} | |
} | |
def list = [5, 4, 3, 2, 1] | |
def sorter = new BubbleSort(list: list) | |
sorter.sort() | |
assert [1, 2, 3, 4, 5] == list |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment