fun mergeSort(list: List<Int>): List<Int> {
// If the list has only one element, it is already sorted
if (list.size <= 1) {
return list
}
// Split the list into two smaller lists
val mid = list.size / 2
val left = list.take(mid)
val right = list.drop(mid)
// Recursively sort the two smaller lists
val leftSorted = mergeSort(left)
val rightSorted = mergeSort(right)
// Merge the two sorted lists together
return merge(leftSorted, rightSorted)
}
// Helper function to merge two sorted lists
fun merge(left: List<Int>, right: List<Int>): List<Int> {
// Create a result list to hold the merged elements
val result = mutableListOf<Int>()
// Iterate through both lists, adding elements to the result list
// as long as the next element is greater than the previous one
while (left.isNotEmpty() && right.isNotEmpty()) {
if (left[0] <= right[0]) {
result.add(left.removeAt(0))
} else {
result.add(right.removeAt(0))
}
}
// Add any remaining elements from the left list
result.addAll(left)
// Add any remaining elements from the right list
result.addAll(right)
return result
}
This function first checks if the list has only one element, in which case it is already sorted and can be returned directly. If the list has more than one element, it is split into two smaller lists, and each of those lists is recursively sorted using the mergeSort function.
The mergeSort function then merges the two sorted lists together using the merge function, which is a helper function that takes in two sorted lists and returns a merged list.
The merge function works by creating a result list and iterating through both input lists. It adds elements to
User
Now create a list with 20 random numbers in Kotlin
Assistant
Here is an example of how you can create a list with 20 random numbers in Kotlin:
code
val randomNumbers = (0..20).map { Random.nextInt(100) }.toList()
This code uses the Random class to generate random integers between 0 and 100, and then uses the map function to transform those integers into a list of random numbers. The toList function is used to convert the result of the map function into a list.
You can also use the random function from the Kotlin Standard Library, which is a part of the Random class, to generate a random number between two specified values, like this:
code
val randomNumbers = (0..20).map { random.nextInt(100) }.toList()
This code uses the random function to generate a random integer between 0 and 100 for each element in the list.