对Scala中的字符串和整数排序列表

时间:2017-09-13 08:50:07

标签: scala list sorting

scala中是否有任何方法可以在不改变相对位置的情况下对整数和字符串进行排序?就像我输入

一样
List("xyz",6,4,"ghi",3,5,1,"abc")

输出应为

List("abc",1,3,"ghi",4,5,6,"xyz")

整数和字符串的相对位置不会改变。我通过单独存储数字和数字的位置然后将不同列表中的字符串和整数排序并将它们放回各自的位置来完成此操作。 Scala中有没有更快的技术?

1 个答案:

答案 0 :(得分:1)

这是一个有效的代码。可能不是最优的,但它解决了这个问题:

object Test {

   def removeElementFromList[T](xs:List[T], t:T):List[T] = xs match {
      case h::tail if h == t => tail
      case h::tail if h != t => h :: removeElementFromList(tail, t)
      case Nil => Nil
   }

  def updateElement[T](xs:List[T], oldValue:T, newValue:T):List[T] = xs match{
    case h::tail if h == oldValue => newValue :: tail
    case h::tail if h != oldValue => h :: updateElement(tail, oldValue, newValue)
    case Nil => Nil
  }

  //ascending
  def sortRetainingPosition[T](xs:List[(T, Int)])(implicit cmp:Ordering[T]):List[(T, Int)] = {
    xs match{
      case h :: tail =>{
        val minimalElement = xs.minBy(_._1)
        if(h == minimalElement) h :: sortRetainingPosition(tail) else{
          (minimalElement._1, h._2) :: sortRetainingPosition(updateElement(tail, minimalElement, (h._1, minimalElement._2)))
        }
      }
      case Nil => Nil
    }
  }

  def main(args:Array[String]):Unit = {
    val input = List("xyz",6,4,"ghi",3,5,1,"abc")
    val positioned = input.zipWithIndex
    val strings = positioned.filter(_._1.isInstanceOf[String]).asInstanceOf[List[(String, Int)]]
    val ints = positioned.filterNot(_._1.isInstanceOf[String]).asInstanceOf[List[(Int, Int)]]
    val partiallySorted = sortRetainingPosition(strings) ++ sortRetainingPosition(ints)
    val result = partiallySorted.sortBy(_._2).map(_._1)
    println(result)
  }
}
相关问题