合并排序不适用于升序

时间:2019-04-23 15:47:13

标签: scala

我正在研究有关scala的课程,在该课程中我将执行合并排序操作。这是为此编写的代码

def merge(leftList:List[Int], rightList:List[Int]): List[Int] = {

  val output = (0 until leftList.length + rightList.length).foldLeft(List[Int](), leftList, rightList) { (triple, _) =>
    val (mergedList, leftRemaining, rightRemaining) = triple
    (leftRemaining, rightRemaining) match {
      case (Nil, r :: rTail) => (r :: mergedList, Nil, rTail)
      case (l :: lTail, Nil) => (l :: mergedList, lTail, Nil)
      case (l :: lTail, r :: rTail) if l > r => (l :: mergedList, lTail, rightRemaining)
      case (l :: lTail, r :: rTail) => (r :: mergedList, leftRemaining, rTail)
    }
  }
  output._1.reverse
}

def mergeSort(inputList: IndexedSeq[Int]): List[Int] = {
  if(inputList.length == 1) List(inputList.head)
  else {
    val (leftList, rightList) = inputList.splitAt(inputList.length / 2)
    val sortedLeft = mergeSort(leftList)
    val sortedRight = mergeSort(rightList)
    merge(sortedLeft, sortedRight)
  }
}

mergeSort(Vector(3,4,1,2,33))

但是,列表不是一直按升序排序,而是始终按降序排序。我尝试调试代码,但未得出任何结论。任何帮助将不胜感激。 我当前的输出如下

res0: List[Int] = List(33, 4, 3, 2, 1)

预期输出为

List(1, 2, 3, 4, 33)

2 个答案:

答案 0 :(得分:1)

这是因为这里:

case (l :: lTail, r :: rTail) if l > r => (l :: mergedList, lTail, rightRemaining)

如果第一个位置l大于r,则您位于第一个位置。如果要升序,则应该相反:

case (l :: lTail, r :: rTail) if l <= r => (l :: mergedList, lTail, rightRemaining)

答案 1 :(得分:1)

解决方案非常简单。您只需将(l> r)更改为(l

请参考以下代码

def merge(leftList:List[Int], rightList:List[Int]): List[Int] = {

  val output = (0 until leftList.length + rightList.length).foldLeft(List[Int](), leftList, rightList) { (triple, _) =>
    val (mergedList, leftRemaining, rightRemaining) = triple
    (leftRemaining, rightRemaining) match {
      case (Nil, r :: rTail) => (r :: mergedList, Nil, rTail)
      case (l :: lTail, Nil) => (l :: mergedList, lTail, Nil)
      case (l :: lTail, r :: rTail) if l < r => (l :: mergedList, lTail, rightRemaining)
      case (l :: lTail, r :: rTail) => (r :: mergedList, leftRemaining, rTail)
    }
  }
  output._1.reverse
}

def mergeSort(inputList: IndexedSeq[Int]): List[Int] = {
  if(inputList.length == 1) List(inputList.head)
  else {
    val (leftList, rightList) = inputList.splitAt(inputList.length / 2)
    val sortedLeft = mergeSort(leftList)
    val sortedRight = mergeSort(rightList)
    merge(sortedLeft, sortedRight)
  }
}

这会产生所需格式的输出

res0: List[Int] = List(1, 2, 3, 4, 33)

如果这能回答您的问题,请告诉我。