scala 排序算法 归并排序
归并(Merge)排序法是将两个(或两个以上)有序表合并成一个新的有
序表,即把待排序序列分为若干个子序列,每个子序列是有序的。然后再把有序子序列合并
为整体有序序列。
序表,即把待排序序列分为若干个子序列,每个子序列是有序的。然后再把有序子序列合并
为整体有序序列。
package com.xing.hai
/**
* Created by xxxx on 3/1/2017.
* 49 38 65 97 76 13 27 49 78 34 12 64 5 4 62 99 98 54 56 17 18 23 34 15 35 25 53 51
* 4 5 12 13 15 17 18 23 25 27 34 34 35 38 49 49 51 53 54 56 62 64 65 76 78 97 98 99
*/
object OrderMergeSort extends App{
val arrayData = Array(49,38,65,97,76,13,27,49,78,34,12,64,5,4,62,99,98,54,56,17,18,23,34,15,35,25,53,51)
arrayData.foreach(x => print(x + " "))
splitDataAndSort(arrayData,0,arrayData.length -1)
println
arrayData.foreach(x => print(x + " "))
def splitDataAndSort(arrayData:Array[Int],left:Int,right :Int): Unit ={
if (left<right){
val center = (left+right)/2
//println(center)
splitDataAndSort(arrayData,left,center)
splitDataAndSort(arrayData,center+1 ,right)
splitedSort(arrayData,left,center,right)
}
}
def splitedSort(arrayData:Array[Int],left:Int,center:Int ,right :Int): Unit ={
val tempArray = new Array[Int](arrayData.length.toInt)
var pointOfTemparray = left
var leftx = left
var midOfright = center + 1
while(leftx <= center && midOfright<= right){
if (arrayData(leftx)< arrayData(midOfright)){
tempArray(pointOfTemparray) = arrayData(leftx)
pointOfTemparray +=1
leftx += 1
}else{
tempArray(pointOfTemparray) = arrayData(midOfright)
pointOfTemparray +=1
midOfright += 1
}
}
while(leftx <= center){
tempArray(pointOfTemparray) = arrayData(leftx)
pointOfTemparray +=1
leftx += 1
}
while(midOfright<= right){
tempArray(pointOfTemparray) = arrayData(midOfright)
pointOfTemparray +=1
midOfright += 1
}
var copyDataBack = left
while (copyDataBack<=right){
arrayData(copyDataBack) = tempArray(copyDataBack)
copyDataBack +=1
}
}
}