DEV Community 👩‍💻👨‍💻

λeo
λeo

Posted on

Kotlin Collections - sort

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)
intArray.sort()
//[1,2,3,4]

With a range of indices

val intArray = intArrayOf(4, 3, 2, 1)
intArray.sort(0,3)
//[2,3,4,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 
people.sort()

println(people) 
// [Ragnar Lodbrok, Bjorn Ironside, Sweyn Forkbeard]

Top comments (0)

🌚 Friends don't let friends browse without dark mode.

Sorry, it's true.