Skip to content

Instantly share code, notes, and snippets.

@rrgroovy
Created November 8, 2011 03:59
Show Gist options
  • Save rrgroovy/1346960 to your computer and use it in GitHub Desktop.
Save rrgroovy/1346960 to your computer and use it in GitHub Desktop.
Reinvention of the Wheel Series, "Bubble Sort in Groovy".
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