Skip to content

Instantly share code, notes, and snippets.

@mwacc
Created September 28, 2013 20:03
Show Gist options
  • Select an option

  • Save mwacc/6745981 to your computer and use it in GitHub Desktop.

Select an option

Save mwacc/6745981 to your computer and use it in GitHub Desktop.
merge sort in groovy
def toSort = [5, 6, 7, 1, 4, 3, 2, 9, 0, 7, 8]
def partition(toSort) {
if(toSort.size == 1) return toSort
int midle = (int)(toSort.size/2)
def left = new ArrayList(), right = new ArrayList();
for(int i = 0; i < midle; i++) left << toSort[i]
for(int i = midle; i < toSort.size; i++) right << toSort[i]
def leftSorted = partition(left)
def rightSorted = partition(right)
def merged = new ArrayList();
int i = 0, j = 0
while( i < leftSorted.size || j < rightSorted.size) {
if(i == leftSorted.size) {
merged << rightSorted[j++]
} else if(j == rightSorted.size) {
merged << leftSorted[i++]
} else if( leftSorted[i] <= rightSorted[j] ) {
merged << leftSorted[i++]
} else {
merged << rightSorted[j++]
}
}
return merged
}
println partition(toSort)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment