Created
October 8, 2015 01:13
-
-
Save cnevinc/65650c72692d60850580 to your computer and use it in GitHub Desktop.
merge sort
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// ============== merge sort start ============== | |
var numbers: IntArray = intArrayOf() | |
var temp: IntArray = intArrayOf() | |
fun merge(low: Int, middle: Int, high: Int) { | |
for (i in low..high) { | |
temp[i] = numbers[i]; | |
} | |
var i = low; | |
var j = middle + 1; | |
var k = low; | |
while (i <= middle && j <= high) { | |
if (temp[i] <= temp[j]) { | |
numbers[k] = temp[i]; | |
i++; | |
} else { | |
numbers[k] = temp[j]; | |
j++; | |
} | |
k++; | |
} | |
while (i <= middle) { | |
numbers[k] = temp[i]; | |
k++; | |
i++; | |
} | |
} | |
fun mergesortImpl(low: Int, high: Int) { | |
if (low < high) { | |
var mid: Int = low + (high - low) / 2; | |
mergesortImpl(low, mid); | |
mergesortImpl(mid + 1, high); | |
merge(low, mid, high); | |
} | |
} | |
fun mergetSort(a: IntArray) { | |
numbers = a; | |
temp = a.copyOf(); | |
mergesortImpl(0, a.size() - 1); | |
} | |
// ============== merge sort end ============== | |
fun main(args: Array<String>) { | |
val array = intArrayOf(7, 6, 5, 4, 3, 2, 1) | |
array.forEach { i -> println(i) } | |
mergetSort(array) | |
array.forEach { i -> println(i) } | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment