DEV Community

λeo
λeo

Posted on

1

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]

Sentry mobile image

Improving mobile performance, from slow screens to app start time

Based on our experience working with thousands of mobile developer teams, we developed a mobile monitoring maturity curve.

Read more

Top comments (0)

Qodo Takeover

Introducing Qodo Gen 1.0: Transform Your Workflow with Agentic AI

Rather than just generating snippets, our agents understand your entire project context, can make decisions, use tools, and carry out tasks autonomously.

Read full post

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay