Jump to content

Sort using a custom comparator: Difference between revisions

m (added category.)
Line 1,819:
printArray("Sorted:", strings)
}</lang>
 
{{out}}
<pre>Unsorted: [Here, are, some, sample, strings, to, be, sorted]
Sorted: [strings, sample, sorted, Here, some, are, be, to]</pre>
 
 
A more idiomatic version (1.3):
 
<lang kotlin>fun main(args: Array<String>) {
val strings = listOf("Here", "are", "some", "sample", "strings", "to", "be", "sorted")
println("Unsorted: $strings")
 
// sort by content first then by length => no need for a custom comparator since sortedByDescending is stable
val sorted = strings.sorted().sortedByDescending { it.length }
println("Sorted: $sorted")
}</lang>
 
 
Using a custom comparator as requested by task description:
 
<lang kotlin>fun main(args: Array<String>) {
val strings = listOf("Here", "are", "some", "sample", "strings", "to", "be", "sorted")
println("Unsorted: $strings")
 
val sorted = strings.sortedWith (
kotlin.Comparator { a, b ->
compareValues(b.length, a.length).let {
if (it == 0) compareValues(a, b)
else it
}
})
println("Sorted: $sorted")
}</lang>
 
 
Faster when computing length only once per value ([[wp:Schwartzian transform|Schwartzian transform]]):
 
<lang kotlin>fun main(args: Array<String>) {
val strings = listOf("Here", "are", "some", "sample", "strings", "to", "be", "sorted")
println("Unsorted: $strings")
 
val sorted = strings.map { Pair(it, it.length) }.sortedWith (
kotlin.Comparator { a, b ->
compareValues(b.second, a.second).let {
if (it == 0) compareValues(a.first, b.first)
else it
}
}).map { it.first }
println("Sorted: $sorted")
}</lang>
 
 
{{out}}
Anonymous user
Cookies help us deliver our services. By using our services, you agree to our use of cookies.