home *** CD-ROM | disk | FTP | other *** search
- with profile
- -------------------------------------
- -- Example Program from the Manual --
- -------------------------------------
-
- function merge_sort(sequence x)
- -- put x into ascending order using a recursive merge sort
- integer n, mid
- sequence merged, x1, x2
-
- n = length(x)
- if n = 0 or n = 1 then
- return x -- trivial case
- end if
-
- mid = floor(n/2)
- x1 = merge_sort(x[1..mid]) -- sort first half of x
- x2 = merge_sort(x[mid+1..n]) -- sort second half of x
-
- -- merge the two sorted halves into one
- merged = {}
- while length(x1) > 0 and length(x2) > 0 do
- if compare(x1[1], x2[1]) < 0 then
- merged = append(merged, x1[1])
- x1 = x1[2..length(x1)]
- else
- merged = append(merged, x2[1])
- x2 = x2[2..length(x2)]
- end if
- end while
- return merged & x1 & x2 -- merged data plus leftovers
- end function
-
- procedure print_sorted_list()
- -- generate sorted_list from list
- ? merge_sort( {9, 10, 3, 1, 4, 5, 8, 7, 6, 2} )
- ? merge_sort( {1.5, -9, 1e6, 100} )
- printf(1, "%s, %s, %s\n", merge_sort({"oranges", "apples", "bananas"}))
- end procedure
-
- print_sorted_list() -- this command starts the program
- profile
-