DEV Community


Kotlin Collections - sort

Code Alchemist
・1 min read

To sort elements in ascending order, use the sort method from the collections package.

The method can receive the start index and final index of the collection range which wants to be sorted.

The method is going to do all the sorting operations in place O(1) and it is going to take O(nlogn) runtime.

val intArray = intArrayOf(4, 3, 2, 1)

With a range of indices

val intArray = intArrayOf(4, 3, 2, 1)

Use the comparable interface to modify the sorting operation

class Person(val firstName: String, val lastName: String) : Comparable<Person> {
    override fun compareTo(other: Person): Int = this.lastName.compareTo(other.lastName)
    override fun toString(): String = "$firstName $lastName"

val people = arrayOf(
    Person("Ragnar", "Lodbrok"),
    Person("Bjorn", "Ironside"),
    Person("Sweyn", "Forkbeard")

//Sorting people collection 

// [Ragnar Lodbrok, Bjorn Ironside, Sweyn Forkbeard]

Discussion (0)