Ascending and descending sorting

Report a typo

It is always nice to have one function that can sort lists both in ascending and descending order. Here is such a sorting function based on the bubble sorting algorithm. It takes exactly two parameters: a list and a comparison function.

You need to create an object that represents a comparison function and assign it to the comparator variable. The comparison function should take 2 parameters and return the lesser one if the sorting order is ascending and the larger one if the order is descending.

Use the isAscending variable to determine the sorting order. If the variable is true, then you need to sort the list in ascending order; otherwise, in descending order.

It is highly recommended to use function references to solve this task. There are several ways to do it, and you can choose any of them. But if it is difficult for you, you can use lambda expressions as well. You can use standard min/max functions or write you own, it's up to you!

By the way, the bubble sorting algorithm is not an efficient function for sorting datasets; here it is just an educational example of how to pass functions to functions.

Sample Input 1:

ascending
3 5 2 1 4

Sample Output 1:

1 2 3 4 5
Write a program in Kotlin
fun main() {
val isAscending: Boolean = readLine()!! == "ascending"
val list: MutableList<Int> = readLine()!!.split(' ').map { it.toInt() }.toMutableList()

val comparator: (Int, Int) -> Int = // put your code here

sort(list, comparator)
list.forEach { e -> print("$e ") }
}

fun sort(array: MutableList<Int>, comparator: (Int, Int) -> Int) {
for (i in 0 until array.size - 1) {
for (j in 0 until array.size - i - 1) {
if (comparator(array[j], array[j + 1]) == array[j + 1]) {
val temp = array[j]
array[j] = array[j + 1]
array[j + 1] = temp
}
}
}
}
___

Create a free account to access the full topic