/ / Scala: Quicksort für eine MutableList [Array [Double]] - Arrays, Liste, Scala, Quicksort

Scala: Quicksort für eine MutableList [Array [Double]] - Arrays, Liste, Scala, Quicksort

Ich benutze ein MutableList[Array[Double]], von denen jedes Array fünf Doubles enthält.

Nun möchte ich einen Quicksort implementieren, der die Liste nach der n-ten Spalte des Arrays sortiert. Ich habe mir das Quicksort-Beispiel auf Rosetta angesehen und mir diese Anpassung vorgenommen:

def quicksortDataByIndex(index: Int, list: MutableList[Array[Double]]): MutableList[Array[Double]] = {
if(list.isEmpty){
list
} else {
val(smaller, bigger) = list partition (_(index) > list.head(index))
quicksortDataByIndex(index, smaller) += list.head ++= quicksortDataByIndex(index, bigger)
}
}
}

Dadurch wird eine ArrayIndexOutOfBounds-Ausnahme am n-ten Element ausgelöst.

Ich gehe davon aus, dass das Schreiben von "_ (Index)" falsch ist, aber ich weiß nicht warum und wie es anders gemacht werden könnte. Vielen Dank!

Antworten:

0 für die Antwort № 1

Das macht was Sie wollen, ich habe gerade das hinzugefügt .tail vor dem Partitionieren.

def quicksortDataByIndex(index: Int, list: MutableList[Array[Double]]) : MutableList[Array[Double]] = {
if(list.isEmpty){
list
} else {
val (smaller, bigger) = list.tail partition (a => a(index) < list.head(index))
quicksortDataByIndex(index, smaller) += list.head ++= quicksortDataByIndex(index, bigger)
}
}

Ausgabe :

quicksortDataByIndex(1, MutableList(Array(0, 3), Array(1, 2), Array(0, 7)))
// MutableList(Array(1.0, 2.0), Array(0.0, 3.0), Array(0.0, 7.0))