zoukankan      html  css  js  c++  java
  • sort & find

    object test {
    
      import Breaks.{break, breakable}
    
    //  def main(args: Array[String]): Unit = {
    //    val a = Array(5, 9, 2, 3, 0, -1)
    //    sort(a, 0, a.length - 1)
    //    a.foreach(println)
    //
    //    println(find(a, 49, 0, a.length - 1))
    //  }
    
    
      def sort(arr: Array[Int], leftBound: Int, rightBound: Int): Unit = {
        val tempVar = arr(leftBound)
        var leftIndex = leftBound
        var rightIndex = rightBound
    
        while (leftIndex < rightIndex) {
          // 右边开始找小的数字
          breakable({
            while (leftIndex < rightIndex) {
              if (arr(rightIndex) < tempVar) {
                arr(leftIndex) = arr(rightIndex)
                leftIndex += 1
                break()
              }
              rightIndex -= 1
            }
          })
    
          breakable({
            while (leftIndex < rightIndex) {
              if (arr(leftIndex) > tempVar) {
                arr(rightIndex) = arr(leftIndex)
                rightIndex -= 1
                break()
              }
              leftIndex += 1
            }
          })
        }
    
        arr(leftIndex) = tempVar
    
        if (leftBound < leftIndex - 1) {
          sort(arr, leftBound, leftIndex - 1)
        }
        if (leftIndex + 1 < rightBound) {
          sort(arr, leftIndex + 1, rightBound)
        }
    
      }
    
      def find(arr: Array[Int], num: Int, leftBound: Int, rightBound: Int): Int = {
        val len = rightBound - leftBound
        if (len >= 0) {
          val index = (leftBound + rightBound) / 2
          if (arr(index) > num) {
            find(arr, num, leftBound, index - 1)
          } else if (arr(index) < num) {
            find(arr, num, index + 1, rightBound)
          } else
            index
        } else {
          -1
        }
      }
    }
    
  • 相关阅读:
    poj 2186 && hdu 3836
    poj 2833 The Average
    hud 3062 Party
    论 ACM 与泡妞 (转载)
    poj 1064 Cable master
    poj Candies
    [转]人才流失的背后
    获取存储过程的ReturnValue值
    javascript js jquery获取元素位置代码总结
    【引用】xmlpath 操作 xml
  • 原文地址:https://www.cnblogs.com/chinashenkai/p/15352023.html
Copyright © 2011-2022 走看看