Skip to content

Instantly share code, notes, and snippets.

@OrdonTeam
Created October 20, 2015 22:47
Show Gist options
  • Save OrdonTeam/46bd35e65edcb7d7f4d6 to your computer and use it in GitHub Desktop.
Save OrdonTeam/46bd35e65edcb7d7f4d6 to your computer and use it in GitHub Desktop.
Qucick sort algorithm using @tailrecursive - Task given by Venkat Subramanian on WJUG 20.11.2016
package com.ordonteam
import groovy.transform.TailRecursive
import spock.lang.Specification
import spock.lang.Unroll
class QSortSpec extends Specification {
@Unroll
def "Should sort all permutations"() {
expect:
qSort([list]) == [1, 2, 3, 4, 5, 6, 7]
where:
list << [1, 2, 3, 4, 5, 6, 7].permutations()
}
@TailRecursive
List<Integer> qSort(List<List<Integer>> lists) {
if (allAreSingle(lists)) {
return merge(lists)
} else {
return qSort(lists.collectMany(this.&splitByPivot))
}
}
boolean allAreSingle(List<List<Integer>> input) {
return input.every { it.size() == 1 }
}
private List<Integer> merge(List<List<Integer>> lists) {
return lists.flatten()
}
private ArrayList<List<Integer>> splitByPivot(List<Integer> subList) {
int pivot = subList[0]
return [
subList.findAll { it < pivot },
[pivot],
subList.findAll { it > pivot }
].findAll()
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment