Re: Sort a List with Integers & Letters
Re: Sort a List with Integers & Letters
- Subject: Re: Sort a List with Integers & Letters
- From: Jon Pugh <email@hidden>
- Date: Tue, 3 Apr 2007 09:01:47 -0700
At 9:57 PM +0100 4/2/07, kai wrote:
>Fortunately, from AppleScript 1.10 (Mac OS X version 10.4), a new considering/ignoring attribute was added - allowing numeric strings to be collated by their numeric value.
Your sort is a bubble sort, which is about the slowest sort known to man. Here's a merge sort, which is among the fastest. I posted this a while ago but have added the considering attribute kai mentions to get the behavior you want.
It seems to work quite well.
Jon
on mergesort(m)
set n to length of m
if n ¾ 1 then
return m
else
set firstList to {}
set secondList to {}
set middleIndex to n div 2
repeat with x from 1 to middleIndex
copy item x of m to end of firstList
end repeat
repeat with x from middleIndex + 1 to n
copy item x of m to end of secondList
end repeat
set firstList to my mergesort(firstList)
set secondList to my mergesort(secondList)
set resultList to my merge(firstList, secondList)
return resultList
end if
end mergesort
on merge(leftList, rightList)
set resultList to {}
repeat while length of leftList > 0 and length of rightList > 0
set a to first item of leftList
set b to first item of rightList
considering numeric strings
if a ¾ b then
copy a to end of resultList
set leftList to rest of leftList
else
copy b to end of resultList
set rightList to rest of rightList
end if
end considering
end repeat
if length of leftList > 0 then
repeat with x in leftList
copy contents of x to end of resultList
end repeat
end if
if length of rightList > 0 then
repeat with x in rightList
copy contents of x to end of resultList
end repeat
end if
return resultList
end merge
set TheList to {"1610G", "121ZB", "114", "13", "21124", "121FB", "250G", "240.25", "1610", "15", "240 25", "240"}
mergesort(TheList)
_______________________________________________
Do not post admin requests to the list. They will be ignored.
AppleScript-Users mailing list (email@hidden)
Help/Unsubscribe/Update your Subscription:
Archives: http://lists.apple.com/archives/applescript-users
This email sent to email@hidden