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
    }
  }
}
posted @ 2021-09-29 11:22  一根咸鱼干  阅读(36)  评论(0编辑  收藏  举报