The 'sort()' method is used to sort a String Array in Ascending order.
fun main() { var arr = arrayOf("Mohan", "John", "Paul", "Kriti", "Salim") arr.sort() println("The Sorted Array in ascending order is : ") for (str in arr) { println(str) } }
The Sorted Array in ascending order is :
So, in the above code we have created a 'Array' and initialised to the variable 'arr'.
Below is how the values are positioned in the Array,
Then we have used the 'sort()' Function to sort the Array 'arr' in ascending order.
And the Array 'arr' gets sorted with 'John' as the first value, 'Kriti' second and 'Mohan' as the third, 'Paul' as fourth and 'Salim' as the fifth value.
And we get the below output.
The Sorted Array in ascending order is :
Even here the 'sort()' method is used to sort the numbers in Increasing Order.
fun main() { var arr = arrayOf(5, 3, 2, 4) arr.sort() println("The Sorted Array in ascending order is : ") for (str in arr) { println(str) } }
The Sorted Array in ascending order is :
So, in the above code we have created an Integer 'Array' and initialised to the variable 'arr'.
Below is how the values are positioned in the Array,
Then we have used the 'Ints()' Function from the 'sort' package to sort the Array 'arr' in increasing order.
And the numbers in the Array 'arr' gets sorted.
And we get the below output.
The Sorted Array in ascending order is :
Even here the 'sortDescending()' method is used to sort the numbers in Decreasing Order.
fun main() { var arr = arrayOf(5, 3, 2, 4) arr.sortDescending() println("The Sorted Array in decreasing order is : ") for (str in arr) { println(str) } }
The Sorted Array in decreasing order is :
Even here the 'sort()' method is used to sort the numbers in Increasing Order by specifying the range.
fun main() { var arr = arrayOf(5, 3, 2, 4) arr.sort(0,2) println("The Sorted Array in increasing order is : ") for (str in arr) { println(str) } }
The Sorted Array in increasing order is :
So, we have the below array,
Now, only the first two values of the array is sorted. And the last two values are left as is.
This is because we have specified the range. i.e. From 0th index to 2nd position(i.e. '1' index).