Re: how to do a proper alphabetical sort?
Re: how to do a proper alphabetical sort?
- Subject: Re: how to do a proper alphabetical sort?
- From: Jon Pugh <email@hidden>
- Date: Thu, 8 Mar 2007 18:33:34 -0800
At 3:42 PM -0800 3/8/07, Patrik B. wrote:
>I am looking for a library or method that does an alphabetical sort?
>
>I need it so that I can write a script that will sort all entries in a
>glossary properly in Indesign CS. The script I have currently does not work
>properly and sorts the characters by ASCII value so a lower case "a" comes
>after a capital "Z" instead of after a capital "A" like it does in a real
>dictionairy.
I just "wrote" something like this for my own sorting needs.
Actually, I took the pseudocode from the Wikipedia and made it work in AppleScript.
It's the mergesort <http://en.wikipedia.org/wiki/Mergesort>:
on mergesort(m)
set n to length of m
if n ¾ 1 then -- less than or equal to
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
if a ¾ b then -- less than or equal to
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 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
-- here's a sample call
mergesort({"Bob", "Carol", "Ted", "Alice"})
You can customize the sort by changing the "a ¾ b" comparison in the merge function.
It works pretty well as is for strings and numbers.
Jon
_______________________________________________
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