Created
May 8, 2013 13:28
-
-
Save jonatasemidio/5540420 to your computer and use it in GitHub Desktop.
QuickSort in aGroovy way!
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
//Estes exemplos podem ser encontrado na wikipedia: http://pt.wikipedia.org/wiki/Quicksort#Groovy | |
//Execute no web groovy console: http://groovyconsole.appspot.com/script/968001 | |
def sort(list) { | |
if (list.isEmpty()) return list | |
anItem = list[0] | |
def smallerItems = list.findAll{it < anItem} | |
def equalItems = list.findAll{it == anItem} | |
def largerItems = list.findAll{it > anItem} | |
sort(smallerItems) + equalItems + sort(largerItems) | |
} | |
//Outra implementação mais compacta para o mesmo algoritimo. | |
//Execute no web groovy console: http://groovyconsole.appspot.com/script/969001 | |
def sort(list) { | |
if (list.size() < 2) return list | |
def items = list.groupBy { it <=> list[0] }.withDefault { [] } | |
sort(items[-1]) + items[0] + sort(items[1]) | |
} | |
//Apesar de ser mais compacta. O fato de utilizarmos o groupBy impossibilita a utilização de uma String como entrada |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment