HyperCard: Script to Sort Multiple Lines (7/92)

Handler Name: quickSort, bubbleSort, merge

This handler, called QuickSort, takes a multiple-line expression and sorts
it into ascending alphabetical order.

function quickSort data
put number of lines in data into lineCount
if lineCount <= 10 then return bubbleSort(data)
return merge(quickSort(line 1 to lineCount div 2 of data),┬
quickSort(line lineCount div 2 + 1 to lineCount of data))
end quickSort

function bubbleSort data
repeat with i = 1 to the number of lines in data
repeat with j = i to the number of lines in data
if line i of data > line j of data then
get line j of data
put line i of data into line j of data
put it into line i of data
end if
end repeat
end repeat
return data
end bubbleSort

function merge list1,list2
put empty into resultList
put 1 into ptr1
put 1 into ptr2
put number of lines in list1 into lineCount1
put number of lines in list2 into lineCount2
repeat until ptr1 > lineCount1 and ptr2 > lineCount2
if ptr1 > lineCount1 then -- use list2
put line ptr2 of list2 & return after resultList
add 1 to ptr2
else if ptr2 > lineCount2 then -- use list1
put line ptr1 of list1 & return after resultList
add 1 to ptr1
else if line ptr1 of list1 < line ptr2 of list2 then
put line ptr1 of list1 & return after resultList
add 1 to ptr1
else
put line ptr2 of list2 & return after resultList
add 1 to ptr2
end if
end repeat
return resultList
end merge


This article is adapted from the Claris Tech Info database.
Published Date: Feb 19, 2012