Guest User

Untitled

a guest
Aug 20th, 2018
1,010
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Kotlin 1.17 KB | None | 0 0
  1. fun mergeSort(list: List<Int>): List<Int> {
  2.   if (list.size <= 1) {
  3.     return list
  4.   }
  5.  
  6.   val left = mutableListOf<Int>()
  7.   val right = mutableListOf<Int>()
  8.  
  9.   val middle = list.size / 2
  10.   list.forEachIndexed { index, number ->
  11.     if (index < middle) {
  12.         left.add(number)
  13.     } else {
  14.         right.add(number)
  15.     }
  16.   }
  17.  
  18.   fun merge(left: List<Int>, right: List<Int>): List<Int> = mutableListOf<Int>().apply {
  19.     var indexLeft = 0
  20.     var indexRight = 0
  21.  
  22.     while (indexLeft < left.size && indexRight < right.size) {
  23.         if (left[indexLeft] <= right[indexRight]) {
  24.               add(left[indexLeft])
  25.               indexLeft++
  26.         } else {
  27.               add(right[indexRight])
  28.               indexRight++
  29.         }
  30.     }
  31.  
  32.     while (indexLeft < left.size) {
  33.         add(left[indexLeft])
  34.         indexLeft++
  35.     }
  36.  
  37.     while (indexRight < right.size) {
  38.         add(right[indexRight])
  39.         indexRight++
  40.     }
  41.   }
  42.  
  43.   return merge(mergeSort(left), mergeSort(right))
  44. }
  45.  
  46. fun main(args: Array<String>) {
  47.   val numbers = listOf(5, 2, 3, 17, 12, 1, 8, 3, 4, 9, 7)
  48.   println("Unsorted: $numbers")
  49.   println("Sorted: ${mergeSort(numbers)}")
  50. }
Advertisement
Add Comment
Please, Sign In to add comment