Re: Sorting of two interdependent sequences
- Posted by petelomax Aug 21, 2012
- 1170 views
I recently faced a similar problem at work. A program like Windows Explorer but MDI, so you could open say C:\Downloads and H:\Archive and drag and drop between the two. I wanted a single copy of the data (which could be directories or database records or whatever) but there was nothing to stop someone opening C:\Downloads in two windows and sorting either by Name/Date/Size/whatever. The solution was a tag sort; each window owned their own tag array but the underlying data remained completely unchanged however they sorted it. Create an array of indexes and sort that, then instead of referencing things via [i], simply reference them via [tag[i]].
sequence Names = {"Army of Lovers", "Boney M.", "C. C. Catch", "Dschinghis Khan"} sequence Numbers = {1987, 1975, 1985, 1979} sequence tags tags = repeat(0,length(Names)) for i=1 to length(tags) do tags[i] = i end for function by_year(integer i, integer j) integer res res = compare(Numbers[i],Numbers[j]) if res=0 then res = compare(Names[i],Names[j]) end if return res end function tags = custom_sort(routine_id("by_year"),tags) for i=1 to length(tags) do printf(1,"Year: %d, Name: %s\n",{Numbers[tags[i]],Names[tags[i]]}) end for
You may need "include sort.e" or "include std/sort.e" at the top. It is trivial to write other custom sort routines, eg by_name would be the same as by_year but with the compare instructions swapped.
Pete