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

I hold an M.Tech degree in Artificial Intelligence (2023) from Delhi Technological University (DTU) and possess over 4 years of experience. I worked at GeeksforGeeks, leading teams and managing content, including GATE CS, Test Series, Placements, C, and C++. I've also contributed technical content to companies like MarsDev, Tutorialspoint, StudyTonight, TutorialCup, and Guru99. My skill set includes coding, Data Structures and Algorithms (DSA), and Object-Oriented Programming (OOPs). I'm proficient in C++, Python, JavaScript, HTML, CSS, Bootstrap, React.js, Node.js, MongoDB, Django, and Data Science.