Sorting an Array of Integers in Kotlin: A Complete Guide

One of the most basic programming activities is sorting, and Kotlin’s simple syntax and extensive library methods make sorting arrays simple and straightforward. This tutorial will cover built-in functions, custom sorting logic, and sophisticated strategies for sorting an array of integers in Kotlin.

1. Understanding Arrays in Kotlin

An array in Kotlin is a collection of elements of a specific type. Unlike lists, arrays have a fixed size and cannot grow or shrink dynamically. Arrays in Kotlin are zero-indexed, meaning the first element has an index of 0.

Creating an Array of Integers

You can create an array of integers using the arrayOf function or the IntArray class.

val array1 = arrayOf(5, 3, 8, 1, 2)
val array2 = intArrayOf(10, 7, 6, 2, 4)

Here, array1 is an Array<Int> and array2 is an IntArray, but both can be sorted using the same methods.

2. Sorting Using Built-in Functions

Kotlin provides several built-in functions to sort arrays effortlessly.

a) sorted() and sortedDescending() Functions

  • sorted() returns a sorted list in ascending order.
  • sortedDescending() returns a sorted list in descending order.

Example:

val numbers = arrayOf(5, 3, 8, 1, 2)

val sortedAsc = numbers.sorted()         // Ascending order
val sortedDesc = numbers.sortedDescending()  // Descending order

println("Ascending: $sortedAsc")        // Output: [1, 2, 3, 5, 8]
println("Descending: $sortedDesc")      // Output: [8, 5, 3, 2, 1]

Note: sorted() and sortedDescending() return a new List and do not modify the original array.

b) sort() Function

If you want to sort the array in place, you can use the sort() function.

Example:

val numbers = intArrayOf(5, 3, 8, 1, 2)

numbers.sort()  // Sorts the array in ascending order
println(numbers.joinToString())  // Output: 1, 2, 3, 5, 8

To sort in descending order:

numbers.sortDescending()
println(numbers.joinToString())  // Output: 8, 5, 3, 2, 1

c) Sorting with sortBy and sortByDescending

For more complex sorting logic, sortBy and sortByDescending can be used with custom criteria.

Example:

val numbers = arrayOf(15, 23, 8, 19, 42)

numbers.sortBy { it % 10 }  // Sort by the last digit
println(numbers.joinToString())  // Output: 42, 23, 15, 8, 19

3. Custom Sorting Logic

Sometimes, built-in sorting functions may not meet your requirements. In such cases, you can implement custom sorting using Comparator or lambdas.

a) Using compareBy and Custom Logic

compareBy allows sorting with custom comparison logic.

Example:

val numbers = arrayOf(5, 13, 8, 2, 20)

numbers.sortWith(compareBy { it % 3 })  // Sort by remainder when divided by 3
println(numbers.joinToString())  // Output: 13, 8, 5, 2, 20

b) Custom Comparator

You can define a custom Comparator for more complex sorting rules.

Example:

val numbers = arrayOf(5, 13, 8, 2, 20)

val customComparator = Comparator { a: Int, b: Int -> 
    (a % 3).compareTo(b % 3) 
}

numbers.sortWith(customComparator)
println(numbers.joinToString())  // Output: 13, 8, 5, 2, 20

4. Sorting in Descending Order

To sort an array in descending order, you can use sortDescending() or provide a custom comparator.

Example:

val numbers = intArrayOf(9, 4, 1, 7, 3)

numbers.sortDescending()
println(numbers.joinToString())  // Output: 9, 7, 4, 3, 1

Alternatively, using a custom comparator:

val numbers = arrayOf(9, 4, 1, 7, 3)

numbers.sortWith(Comparator { a, b -> b - a })  // Descending order
println(numbers.joinToString())  // Output: 9, 7, 4, 3, 1

5. Sorting Mutable and Immutable Arrays

  • Mutable Arrays: Use IntArray, Array<Int>, or mutableListOf to sort in-place.
  • Immutable Arrays: Use sorted() to return a new sorted list.

Mutable Example:

val mutableArray = mutableListOf(7, 5, 2, 1, 9)
mutableArray.sort()
println(mutableArray)  // Output: [1, 2, 5, 7, 9]

Immutable Example:

val immutableArray = listOf(7, 5, 2, 1, 9)
val sortedList = immutableArray.sorted()
println(sortedList)  // Output: [1, 2, 5, 7, 9]

6. Sorting with Lambdas

Kotlin’s support for lambda expressions makes it easy to sort arrays using custom conditions.

Example:

val numbers = arrayOf(11, 22, 33, 44, 55)

numbers.sortWith { a, b -> (a % 10) - (b % 10) }
println(numbers.joinToString())  // Output: 11, 22, 33, 44, 55

Here, the sorting is based on the last digit of each number.

7. Real-world Use Case: Sorting with Conditions

Let’s sort an array based on multiple criteria. For example, sort by even numbers first, then odd numbers.

Example:

val numbers = arrayOf(1, 3, 4, 8, 5, 9, 2)

numbers.sortWith(Comparator { a, b ->
    when {
        (a % 2 == 0 && b % 2 != 0) -> -1  // Even before odd
        (a % 2 != 0 && b % 2 == 0) -> 1   // Odd after even
        else -> a - b                     // Natural order
    }
})

println(numbers.joinToString())  // Output: 2, 4, 8, 1, 3, 5, 9

8. Conclusion

Kotlin makes sorting arrays of integers both simple and powerful. Whether you use the built-in sorting functions or implement custom comparators, Kotlin provides the flexibility to handle complex sorting logic. By mastering array sorting, you can tackle a wide range of real-world problems more efficiently.