|
|
Sort lists in AppleScript using the Unix sort command
You are probably better off just implementing your own sort. That way you can sort any item without coercing it to text and then having to coerce it back.
on BubbleSort(theList)
if class of theList is list then
set theSize to length of theList
repeat with i from 1 to theSize
repeat with j from 2 to (theSize - i + 1)
if ((item (j - 1) of theList) > (item j of theList)) then
set temp to (item (j - 1) of theList)
set (item (j - 1) of theList) to (item j of theList)
set (item j of theList) to temp
end if
end repeat
end repeat
return theList
else
return false
end if
end bubblesort
set the_list to {"c", "b", "e", "a", "d"}
BubbleSort(the_list)
This will sort any list that contains items which can be compared with each other using the greater than (>) operator. The list should also only contain one class of item in it, having a list that contains multiple classes of items could have odd results in the sorting. These conditions would be also be true when using the "sort" command in the shell.
Sort lists in AppleScript using the Unix sort command
Bubblesort is a good ol' good one, but it is intolerably slow. Compare the original post's UNIX handler and the BubbleSort handler using this as your list:
It's no contest.
Sort lists in AppleScript using the Unix sort command
While the bubble sort routine is not the speediest, there are other vanilla AppleScript methods for sorting that are much faster and have the added benefit of keeping the data as the native data types without coercing to strings. For instance, here is a comparison using the shell sort example with the quick sort method developed by a few very accomplished AppleScripters (I'm not sure who at this point: HAS? AK? NG?)
Jon
Sort lists in AppleScript using the Unix sort command
Sure, bubblesort is slow for a large number of items. That's why I said that I have a bunch of different types of sorts programmed in AppleScript. If I want to sort a large list I'd use a quicksort or a heapsort, they are O(nlogn) - much faster than bubblesort which is O(n^2). If I really needed efficient sorting I would combine a quicksort and an insertion sort (for when the quicksort partition is 10 elements or less). However, if I'm sorting a ton of elements and time is a factor then AppleScript is the wrong tool in the first place... |
SearchFrom our Sponsor...Latest Mountain Lion HintsWhat's New:HintsNo new hintsComments last 2 daysLinks last 2 weeksNo recent new linksWhat's New in the Forums?
Hints by TopicNews from Macworld
From Our Sponsors |
|
Copyright © 2014 IDG Consumer & SMB (Privacy Policy) Contact Us All trademarks and copyrights on this page are owned by their respective owners. |
Visit other IDG sites: |
|
|
|
Created this page in 0.09 seconds |
|