Skip to main content

How to sort an array in Kotlin

How to sort an array in Kotlin.

Here's a step-by-step tutorial on how to sort an array in Kotlin:

Step 1: Create an Array

First, you need to create an array that you want to sort. You can initialize an array with elements using the arrayOf function. For example, to create an array of integers, you can use the following code:

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

Step 2: Sorting in Ascending Order

To sort the array in ascending order, you can use the sort function. This function sorts the elements of the array in-place, meaning it modifies the original array. Here's an example:

numbers.sort()

After executing this code, the numbers array will be sorted in ascending order: [1, 2, 3, 5, 8].

Step 3: Sorting in Descending Order

If you want to sort the array in descending order, you can use the sortDescending function. This function is similar to sort, but it sorts the elements in descending order. Here's an example:

numbers.sortDescending()

After executing this code, the numbers array will be sorted in descending order: [8, 5, 3, 2, 1].

Step 4: Sorting with Custom Comparator

Sometimes, you may need to sort an array based on a custom comparison logic. In Kotlin, you can use the sortWith function to achieve this. The sortWith function takes a comparator as a parameter, which defines the comparison logic. Here's an example that sorts an array of strings based on their lengths:

val names = arrayOf("Alice", "Bob", "Charlie", "David")
names.sortWith(compareBy { it.length })

After executing this code, the names array will be sorted based on the lengths of the strings: ["Bob", "Alice", "David", "Charlie"].

Step 5: Sorting with Comparator in Descending Order

To sort an array using a custom comparator in descending order, you can use the sortedWith function. This function returns a new sorted list without modifying the original array. Here's an example:

val grades = arrayOf(90, 80, 95, 85)
val sortedGrades = grades.sortedWith(compareByDescending { it })

After executing this code, the sortedGrades array will contain the sorted grades in descending order: [95, 90, 85, 80].

That's it! You now know how to sort an array in Kotlin using various methods.