Newbie
Newbie

Reputation: 21

Saving the index from a real list

I'm trying to declare a function sort : real list -> int list * real list that sorts the list using mergesort and also returns an int list with the original positions of the individual numbers pre-sort.

Maybe this example will make it easier to understand:

sort [5.4,7.2,1.5,9.6] = ([2,0,1,3], [1.5,5.4,7.2,9.6]

Now the sorting of the list is pretty easy, but I'm having a hard time figuring out how to get it to remember the original position and then make an int list with it.

Help?

Upvotes: 2

Views: 104

Answers (1)

sepp2k
sepp2k

Reputation: 370397

  1. Create a list of pairs that contains each item of the original list with its index (you can use ListPair.zip with a list of the indices (that you can create with List.tabulate), to do this).
  2. Sort that list.
  3. Use ListPair.unzip to turn the sorted list of pairs into a pair of lists.

Upvotes: 1

Related Questions