This file contains 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
def quickSort(list) { | |
/*Make sure there are at least 2 elements in the list*/ | |
if (list == null || list.size() < 2) { | |
return list | |
} | |
/*break the list to three different groups | |
group 1: with elements less than pivot | |
group 2: with elements equal to pivot | |
group 3: with elements greater than pivot */ | |
def partitions = list.groupBy { it <=> list[0] }.withDefault { [] } | |
/* sort group 1 and 3 and merge them with group 3 */ | |
return quickSort(partitions[-1]) + partitions[0] + quickSort(partitions[1]) | |
} | |
assert [] == quickSort([]) | |
assert [1] == quickSort([1]) | |
assert [1,5] == quickSort([5, 1]) | |
assert [1,2,3,4,5] == quickSort([5,1,4,3,2]) |
No comments:
Post a Comment