Sorting two lists by contents of one of them

Some time ago (can’t find the thread) Kai posted a handler for sorting a list of file names according to their modification dates. I’m trying to use that to sort a list of calendar events according to the date of the event. I’ve boiled it down to this:


set tList to {4, 1, 5, 3, 6, 2} -- in the order of the dates below.
set tDates to {date "Tuesday, June 6, 2006 11:00:00 AM", date "Thursday, April 20, 2006 12:00:00 PM", date "Wednesday, July 12, 2006 12:00:00 PM", date "Tuesday, May 30, 2006 12:00:00 PM", date "Tuesday, August 1, 2006 11:30:00 AM", date "Wednesday, May 17, 2006 12:00:00 PM"}

sort_items(tList, tDates)

to sort_items(theList, sort_by) -- Kai's dual list sorter
	script o
		property tL : theList
		property sB : sort_by
	end script
	repeat with j from 2 to count o's tL
		set v to o's sB's item j
		set w to o's tL's item j
		repeat with j from j to 2 by -1
			set j to j - 1
			tell o's sB's item j to if v < it then
				set o's sB's item j to it
				set o's tL's item j to o's tL's item j
			else
				set o's sB's item j to v
				set o's tL's item j to w
				exit repeat
			end if
		end repeat
		if j is 2 and v < o's sB's item 1 then
			set o's sB's item 1 to v
			set o's tL's item 1 to w
		end if
	end repeat
end sort_items

This returns two lists now sorted and both are wrong (though they match, of course). tList, which should have come out as {1, 2, 3, 4, 5, 6} is actually found to be: {4, 5, 5, 6, 6, 2}.

Where have I gone wrong?

Got it with this modification (to a script by Kai). The lists aren’t large enough to warrant a script object in the handler.


set tList to {4, 1, 5, 3, 6, 2} -- intentionally ordered like the dates for easy checking.
set tDates to {date "Tuesday, June 6, 2006 11:00:00 AM", date "Thursday, April 20, 2006 12:00:00 PM", date "Wednesday, July 12, 2006 12:00:00 PM", date "Tuesday, May 30, 2006 12:00:00 PM", date "Tuesday, August 1, 2006 11:30:00 AM", date "Wednesday, May 17, 2006 12:00:00 PM"}

sort_items(tDates, tList)

to sort_items(sortList, SecondList) 
-- sorts sortList in place (without a new list or index list) and performs the same swap operations on SecondList.
	tell (count sortList) to repeat with i from (it - 1) to 1 by -1
		set s to sortList's item i
		set r to SecondList's item i
		repeat with i from (i + 1) to it
			tell sortList's item i to if s > it then
				set sortList's item (i - 1) to it
				set SecondList's item (i - 1) to SecondList's item i
			else
				set sortList's item (i - 1) to s
				set SecondList's item (i - 1) to r
				exit repeat
			end if
		end repeat
		if it is i and s > sortList's end then
			set sortList's item it to s
			set SecondList's item it to r
		end if
	end repeat
end sort_items