Fundamental Sorting in Kotlin: Using the sort() Function

By | September 30, 2023

Sorting is one of the most fundamental thing in all programming languages. One of the Simple Approach is to use sort() function in Kotlin. In Kotlin any Data types of an Array can be sorted using sort() function.

In sort() function there are two types :

  1. Without passing parameters.
  2. With passing parameters.

1. Without passing parameters :

In Kotlin we can use sort() function without passing any parameters to sort the whole array.

Examples :

Input : val intArray = intArrayOf(4, 3, 2, 1)
           intArray.sort()
Output : 1 2 3 4

Input : val intArray = intArrayOf(7, 3, 2, 8)
          intArray.sort()
Output : 2 3 7 8

Kotlin program to sort an array using sort()

// Kotlin program to sort the array
fun main(args: Array<String>){
    // Declaring an array using intArrayOf()
    val intArray = intArrayOf(4, 3, 2, 1)

    // Sorting the array using sort()
    intArray.sort()

    // Printing the array after sorting
    for (i in 0..intArray.size-1)
    {
        print(" "+intArray[i])
    }
}

Output :

1 2 3 4

2. With passing parameters :

In Kotlin we can use sort an array in range using sort(fromIndex, toIndex) which sorts a range in the array in-place.

Syntax : 

sort(fromIndex, toIndex)

fromIndex - the start of the range(inclusive) to sort, 0 by default.
toIndex - the end of the range(exclusive) to sort, size of this array by default.

Examples :

Input : val intArray = intArrayOf(4, 3, 2, 1)
           intArray.sort(0, 3)
        
Output : 2 3 4 1

Input : val intArray = intArrayOf(5, 3, 2, 1, 6)
           intArray.sort(0, 2)        
        
Output : 3 5 2 1 6

Kotlin program to sort an array using sort(fromIndex, toIndex)

// Kotlin program to sort the array
fun main(args: Array<String>){
    // Declaring an array using intArrayOf()
    val intArray = intArrayOf(4, 3, 2, 1)

    // Sorting the array using sort(fromIndex, toIndex)
    intArray.sort(0, 3)

    // Printing the array after sorting in range
    for (i in 0..intArray.size-1)
    {
        print(" "+intArray[i])
    }
}

Output :

2 3 4 1

Please write comments if you find anything incorrect. A gentle request to share this topic on your social media profile.

Author: Mithlesh Upadhyay

Mithlesh Upadhyay is a Computer Science and AI expert from Madhya Pradesh with strong academic background (BE in CSE and M.Tech in AI) and over six years of experience in technical content development. He has contributed tech articles, led teams, and worked in Full Stack Development and Data Science. He founded the w3colleges.org portal for learning resources.