Created
December 5, 2014 09:04
-
-
Save silverprize/74fef89651259fd56c0d to your computer and use it in GitHub Desktop.
Mergesort with scala
This file contains 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
object MergeSort { | |
def sort(source: Array[Int]): Unit = { | |
branch(source, 0, source.length) | |
} | |
private def sortAndMerge(source: Array[Int], | |
offset0: Int, len0: Int, | |
offset1: Int, len1: Int): Unit = { | |
val buffer = new Array[Int](len0 + len1) | |
var idx0 = offset0 | |
var idx1 = offset1 | |
val end0 = offset0 + len0 | |
val end1 = offset1 + len1 | |
for (idx <- 0 until buffer.length) { | |
if (idx0 == end0) { | |
buffer(idx) = source(idx1) | |
idx1 += 1 | |
} else if (idx1 == end1) { | |
buffer(idx) = source(idx0) | |
idx0 += 1 | |
} else if (source(idx0) < source(idx1)) { | |
buffer(idx) = source(idx0) | |
idx0 += 1 | |
} else { | |
buffer(idx) = source(idx1) | |
idx1 += 1 | |
} | |
} | |
for (i <- 0 until buffer.length) { | |
source(offset0 + i) = buffer(i) | |
} | |
} | |
private def branch(source: Array[Int], offset: Int, len: Int): Unit = { | |
val half = len / 2 | |
if (half > 1) { | |
branch(source, offset, half) | |
} | |
if (len - half > 1) { | |
branch(source, offset + half, len - half) | |
} | |
sortAndMerge(source, offset, half, offset + half, len - half) | |
} | |
} | |
object Main { | |
def main(args: Array[String]) { | |
def makeSource(size: Int, maxVal: Int): Array[Int] = { | |
val arr = new Array[Int](size) | |
for (i <- 0 until size) { | |
arr(i) = Random.nextInt(maxVal) | |
} | |
arr | |
} | |
val source = makeSource(20, 50) | |
source.foreach((x: Int) => print(x + " ")) | |
println() | |
MergeSort.sort(source) | |
for (elem <- source) { | |
print(elem + " ") | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment