guanaco-33b· University of Washington
Arena Human Preference 55K
Write a Kotlin function to merge sort to lists
- User
Write a Kotlin function to merge sort to lists
- Assistant
Here is an implementation of a merge sort function in Kotlin to sort a list of integers:
fun mergeSort(list: List<Int>): List<Int> { if (list.size <= 1) return list val middle = list.size / 2 val left = list.subList(0, middle) val right = list.subList(middle, list.size) return merge(mergeSort(left), mergeSort(right)) } fun merge(left: List<Int>, right: List<Int>): List<Int> { var result = ArrayList<Int>() while (left.isNotEmpty() && right.isNotEmpty()) { if (left.first() < right.first()) { result.add(left.first()) left.removeAt(0) } else { result.add(right.first()) right.removeAt(0) } } if (left.isNotEmpty()) { result.addAll(left) } if (right.isNotEmpty()) { result.addAll(right) } return result }In this implementation, the
mergeSortfunction divides the list into two sub-lists recursively until they are of size 1 or 0, and then merges the sorted sub-lists together to form the final sorted list. Themergefunction takes two lists and merges them together, placing the smaller element in the final result. - User
Now create a list with 20 random numbers in Kotlin
- Assistant
Here's an example of how to create a list of 20 random numbers in Kotlin:
val random = Random() val list = listOf<Int>(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20) val randomList = listOf<Int>() for (i in 0 until 20) { val randomNumber = random.nextInt(list.size) randomList.add(list[randomNumber]) list.removeAt(randomNumber) }
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.