/**
* 归并排序
*
* @param a
* @param low
* @param high
*/
def mergeSort(a: Array[Int], low: Int, high: Int): Unit = {
val mid = (low + high) / 2
if (low < high) {
// 左边
mergeSort(a, low, mid)
// 右边
mergeSort(a, mid + 1, high)
// 左右归并
merge(a, low, mid, high)
}
}
//合并两个数列
def merge(a: Array[Int], low: Int, mid: Int, high: Int): Unit = {
// 左指针
var i = low
// 右指针
var j = mid + 1
val temp = new Array[Int](high - low + 1)
var k = 0
// 把较小的数先移到新数组中
while (i <= mid && j <= high) {
if (a(i) < a(j)) {
temp(k) = a(i)
i += 1
} else {
temp(k) = a(j)
j += 1
}
k += 1
}
// 把左边剩余的数移入数组
while (i <= mid) {
temp(k) = a(i)
k += 1
i += 1
}
// 把右边边剩余的数移入数组
while (j <= high) {
temp(k) = a(j)
k += 1
j += 1
}
// 把新数组中的数覆盖nums数组
var n = 0
while (n < temp.length) {
a(n + low) = temp(n)
n += 1
}
}