Re: Fastest Alphabetizer(sorter) for Lists
Re: Fastest Alphabetizer(sorter) for Lists
- Subject: Re: Fastest Alphabetizer(sorter) for Lists
- From: Jason Bourque <email@hidden>
- Date: Tue, 01 May 2001 20:31:28 -0400
>
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.
Sounds good. . .
>
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
I'm with you. . .
>
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
Still good. . .
>
set str to "20"
>
set num to 20
>
>
CompareAsStrings(str, num) -- > 0, "20" is equal to 20
Ok, made it thus far. . .
>
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:
Interesting, hadn't thought of that. . .
>
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"}
Ok, makes sense. . .
>
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
Oops, you lost me. What is "missing value"(I forgot this lovely piece when
first testing the script you sent me.)
>
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
Now I will see if I can unravel the logic of the sort. . .
Thank you.
Jason Bourque