Ok
Let it start from the very beginning. Besides the fact that you look at the unsorted list every time, the Seq object creates a List collection by default. So in foldLeft you add an item at the end of the list every time, and this is O(N^2) operation.
Improvement will be
val sorted_rev = index.foldLeft(Seq[Int]()) { (s, num) => unsorted.find(_ == num).get +: s } val sorted = sorted_rev.reverse
But this is still an O(N^2) algorithm. We can do better.
The following sort function should work:
def sort[T: ClassTag, Key](index: Seq[Key], unsorted: Seq[T], key: T => Key): Seq[T] = { val positionMapping = HashMap(index.zipWithIndex: _*) //1 val arr = new Array[T](unsorted.size) //2 for (item <- unsorted) { //3 val position = positionMapping(key(item)) arr(position) = item } arr //6 }
The function sorts the list of unsorted elements using a sequence of indexes index , where the key function will be used to extract the identifier from the objects you are trying to sort.
Line 1 creates a reverse index - mapping each object identifier to its final position.
Line 2 allocates an array that will contain the sorted sequence. We use an array, because we need constant job performance in an arbitrary position.
The loop that starts on line 3 will traverse the sequence of unsorted elements and put each element at that value using the positionMapping index, the inverse index
Line 6 will return an array converted implicitly to Seq using the WrappedArray wrapper.
Since our reverse index is a constant HashMap , the search should take constant time for regular cases. Building the actual inverse index takes O(N_Index) time, when N_Index is the size of the index sequence. Passing an unsorted sequence takes O(N_Unsorted) time, when N_Unsorted is the size of the unsorted sequence.
So the complexity is O(max(N_Index, N_Unsorted)) , and I think this is the best thing you can do in the circumstances.
In your specific example, you call the function as follows:
val sorted = sort(index, unsorted, identity[Int])
For a real case, this is likely to be as follows:
val sorted = sort(idList, unsorted, obj => obj.id)