zoukankan      html  css  js  c++  java
  • scala 排序算法 归并排序

    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
        }
      }
    }
    


  • 相关阅读:
    配色方案及色彩心理学(转)
    CSS中强大的EM
    Link To Sql简单
    改变html中鼠标形状
    JS实现雪花效果
    你真的已经搞懂JavaScript了吗?
    MVC特性
    初识 bower(一)
    学习前端模板引擎 jade (一)
    日志系统
  • 原文地址:https://www.cnblogs.com/TendToBigData/p/10501273.html
Copyright © 2011-2022 走看看