Re: Fastest Alphabetizer(sorter) for Lists
Re: Fastest Alphabetizer(sorter) for Lists
- Subject: Re: Fastest Alphabetizer(sorter) for Lists
- From: "Arthur J Knapp" <email@hidden>
- Date: Tue, 01 May 2001 10:19:45 -0400
>
Date: Mon, 30 Apr 2001 21:40:51 -0400
>
Subject: Fastest Alphabetizer(sorter) for Lists
>
From: Jason Bourque <email@hidden>
>
Make a list containing both numbers and words alphabetized.
>
Does anyone have the sorting routine that was deemed the fastest?
Let's slow down first and establish what it is that you are asking
for. You want to sort both numbers and strings, in the same list, is
that right? Then you need to decide what set of "rules" you want to
follow for when the script goes to compare a number and a string.
It is simple enough to temporarily coerce a number to a string
for the purposes of comparison:
set str to "2% Milk"
set num to 20
CompareAsStrings(str, num) -- > -1, "2%" sorts before 20
set str to "email@hidden"
set num to 20
CompareAsStrings(str, num) -- > 1, "2@" sorts after 20
set str to "20"
set num to 20
CompareAsStrings(str, num) -- > 0, "20" is equal to 20
on CompareAsStrings(a, b)
set a to a as string
set b to b as string
if a < b then
return -1
else if a > b then
return 1
else
return 0
end if
end CompareAsStrings
but this may not be what it is that you are looking for.
Sometimes, it is convient to simply separate the different classes
into their own lists:
set myList to {2, "abc", 35, "48"}
set myNumbers to every number of myList
set myStrings to every string of myList
qSort( myNumbers, 1, length of myNumbers )
qSort( myStrings, 1, length of myNumbers )
set myList to myNumbers & myStrings
-- > {2, 35, "48", "abc"}
Here is another way to implement the quicksort handler:
set myList to {20, "2% Milk", "email@hidden"}
SortAsStrings(myList)
myList
-- > {"2% Milk", 20, "email@hidden"}
property qsort_compare : missing value
on CompareAsStrings(a, b)
set a to a as string
set b to b as string
if a < b then
return -1
else if a > b then
return 1
else
return 0
end if
end CompareAsStrings
to SortAsStrings(lst)
set qsort_compare to CompareAsStrings
qSort(lst, 1, length of lst)
set qsort_compare to missing value
end SortAsStrings
to qSort(lst, l, r)
set {a, z, v} to {l, r, lst's item ((l + r) div 2)}
repeat until z is less than or equal to a
repeat while qsort_compare(item a of lst, v) < 0
set a to a + 1
end repeat
repeat while qsort_compare(item z of lst, v) > 0
set z to z - 1
end repeat
if a is less than or equal to z then
set {lst's item z, lst's item a, a, z} to ,
{lst's item a, lst's item z, a + 1, z - 1}
end if
end repeat
if l < z then qSort(lst, l, z)
if r > a then qSort(lst, a, r)
end qSort
Arthur J. Knapp
http://www.stellarvisions.com
mailto:email@hidden
Hey, check out:
<
http://developer.apple.com/techpubs/macos8/InterproCom/AppleScriptScripters
/AppleScriptLangGuide/>