quicksort in Lingo


[ Zettels Traum ] [ search / suche ]

von dp am 23.August 98 um 18:24:31:

>Could some kind soul post a basic example of this recurvise programming
>technique. I would very much appreciate it.
>
Here is an example of the recursive QuickSort algorithm, written in Lingo:
-- quicksort algorithm
-- set val to qsort([3,2,1])
on qsort list
  -- check to see if the list needs sorting
  if count(list) > 1 then
    -- use the first element as a pivot
    set p to getat(list,1)
    deleteat(list,1)
    -- sort the remaining list into 2 lists, greater and less than the pivot
    set z to pivot(list,p)
    -- sort the lesser list
    set z1 to qsort(getat(z,1))
    -- add the pivot to the end
    append(z1,p)
    -- sort the greater list
    set z2 to qsort(getat(z,2))
    -- append the lists
    set list to app(z1,z2)
  end if
  return list
end
-- split the list x based on pivot point p
on pivot x,p
  set a to []
  set b to []
  repeat with y in x
    if y <= p then 
      add(a,y)
    else
      add(b,y)
    end if
  end repeat
  return [a,b]
end
-- append 2 lists together
on app x,y
  repeat with z in y
    append(x,z)
  end repeat
  return x
end

Note that the qsort function is recursive because it calls itself twice within its own function.





Dazu:























D. Plänitz