6 different ways to sort an array in Kotlin

How to sort an array in Kotlin :

Sorting an array is easy in Kotlin. Kotlin provides different built-in functions to make it easier. In this tutorial, I will show you different ways to sort an array in Kotlin. You will learn how to sort a simple array and how to sort an array of custom objects in this tutorial post.

Method 1: Sort an array in ascending order using sort() :

The sort() function can be used to sort the array elements in ascending order. The syntax of the sort() function is:

fun > Array.sort()

It will sort the array in place as its natural order of the elements. For example:

import java.util.*

fun main() {
    val students = arrayOf(10,9,23,12,5,2,4,1)
    println("Original array : ${Arrays.toString(students)}")

    students.sort()
    println("Sorted array : ${Arrays.toString(students)}")
}

Download it on Github

It will print the below output:

Original array : [10, 9, 23, 12, 5, 2, 4, 1]
Sorted array : [1, 2, 4, 5, 9, 10, 12, 23]

kotlin sort array

Note that this function will modify the original array.

Method 2: Sort an array in ascending order within a range:

We can use the sort(from,to) function to sort an array within a range. It takes two parameters: the first parameter is the index to start the sort(inclusive) and the second parameter is the index to end the sort(exclusive). If you pass 0 and 5 to these parameters respectively, it will only sort the elements starting from the 0th position to the 4th position, leaving other elements unchanged. This function is defined as below:

public fun  Array.sort(fromIndex: Int = 0, toIndex: Int = size)

Example of Array.sort:

The following example shows how to use the Array.sort method with the range values:

import java.util.*

fun main() {
    val students = arrayOf(10,9,8,7,6,5,4,3,2,1)
    println("Original array: ${Arrays.toString(students)}")

    students.sort(0,5)
    println("Sorted array from index 0 to 5: ${Arrays.toString(students)}")
}

Download it on Github

Output:

Original array: [10, 9, 8, 7, 6, 5, 4, 3, 2, 1]
Sorted array from index 0 to 5: [6, 7, 8, 9, 10, 5, 4, 3, 2, 1]

As you can see, it sorts only the first 5 elements, i.e. elements from index 0 to index 4 of the array students.

kotlin sort array

Method 3: Sort an array in descending order:

The sortDescending() method is used to sort an array in descending order. Similar to the sort() method, it will sort the array in place. The syntax of this function is as below:

public fun > Array.sortDescending()

Example of the sortDescending method:

The following program shows how to use the sortDescending method:

import java.util.*

fun main() {
    val students = arrayOf(1,5,7,8,2,3,9,10)
    println("Original array: ${Arrays.toString(students)}")

    students.sortDescending()
    println("Sorted array: ${Arrays.toString(students)}")
}

Download it on Github

If you run the above program, it will print:

Original array: [1, 5, 7, 8, 2, 3, 9, 10]
Sorted array: [10, 9, 8, 7, 5, 3, 2, 1]

Similar to the sort() method, we can also pass the from and to parameters to this function to sort only a part of the array:

import java.util.*

fun main() {
    val students = arrayOf(1,2,3,4,5,6,7,8,9,10)
    println("Original array: ${Arrays.toString(students)}")

    students.sortDescending(0, 5)
    println("Sorted array from index 0 to 5: ${Arrays.toString(students)}")
}

Download it on Github

Output:

Original array: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
Sorted array from index 0 to 5: [5, 4, 3, 2, 1, 6, 7, 8, 9, 10]

It sorted the array from index 0 to 4 in descending order.

Method 4: Sort and return a new array without modifying the original array:

The sortedArray() and sortedArrayDescending functions are used to sort an array and return a new array instead of modifying the original array. Let’s have a look at the below program:

fun main() {
    val students = arrayOf(5,2,6,9,10,1,44,23)
    println("Original array: ${students.contentToString()}")

    val sortedArray = students.sortedArray()
    println("Sorted array: ${sortedArray.contentToString()}")

    val descendingSortedArray = students.sortedArrayDescending()
    println("Sorted array in descending: ${descendingSortedArray.contentToString()}")
}

Download it on Github

It will print the below output:

Original array: [5, 2, 6, 9, 10, 1, 44, 23]
Sorted array: [1, 2, 5, 6, 9, 10, 23, 44]
Sorted array in descending: [44, 23, 10, 9, 6, 5, 2, 1]

The original array students remained unchanged in this example.

kotlin sort array

Instead of an Array, if you want to return a list, you can use the sorted() and sortedDescending() functions.

Method 5: Sort an array of custom objects using a comparator:

We can use the sortWith function to sort an array of custom objects. It takes one comparator as a parameter and sorts the array using the function defined by the comparator.

fun main() {
    val students = arrayOf(Student("Alex", 5), Student("Bob", 2), Student("Harry", 1))

    println("Original array:")
    students.forEach { println(it) }

    students.sortWith(Comparator { s1: Student, s2: Student -> s1.rank - s2.rank })

    println("Final array:")
    students.forEach { println(it) }
}

data class Student(val name: String, val rank: Int)

Download it on Github

Output:

Original array:
Student(name=Alex, rank=5)
Student(name=Bob, rank=2)
Student(name=Harry, rank=1)
Final array:
Student(name=Harry, rank=1)
Student(name=Bob, rank=2)
Student(name=Alex, rank=5)

As you can see, the original array is sorted as per the rank. The sorting is done in place.

  • sortWith(comparator: Comparator,fromIndex: Int = 0,toIndex: Int = size) method can be used to sort an array within a range.
  • sortedArrayWith(comparator: Comparator) method can be used to return an array instead of sorting the array in place.
  • The sortedWith(comparator: Comparator) method returns a list.

Method 6: Sort an array of custom objects using a selector function:

Instead of a comparator, we can also pass a selector function to the sortBy function to sort an array. For example:

fun main() {
    val students = arrayOf(Student("Alex", 5), Student("Bob", 2), Student("Harry", 1))

    println("Original array:")
    students.forEach { println(it) }

    students.sortBy { student -> student.rank}

    println("Final array:")
    students.forEach { println(it) }
}

data class Student(val name: String, val rank: Int)

Download it on Github

It will print:

Original array :
Student(name=Alex, rank=5)
Student(name=Bob, rank=2)
Student(name=Harry, rank=1)
Final array :
Student(name=Harry, rank=1)
Student(name=Bob, rank=2)
Student(name=Alex, rank=5)

This function also modifies the array in place.

  • The sortByDescending(crossinline selector: (T) -> R?) can sort an array in descending order(in-place).
  • The sortedBy(selector: (T) -> R?) method returns a list.
  • The sortedByDescending(selector: (T) -> R?) method returns a list in descending order.

Conclusion:

In this tutorial, we learned how to sort elements of an array in kotlin with different functions. Try to run these examples and try to implement complex examples with different comparators and selectors. You can also raise a PR on Github if I missed anything.

You might also like: