quicksort.awk 1.0 KB

1234567891011121314151617181920212223242526272829303132333435
  1. # quicksort.awk --- Quicksort algorithm, with user-supplied
  2. # comparison function
  3. #
  4. # Arnold Robbins, arnold@skeeve.com, Public Domain
  5. # January 2009
  6. # quicksort --- C.A.R. Hoare's quicksort algorithm. See Wikipedia
  7. # or almost any algorithms or computer science text.
  8. #
  9. # Adapted from K&R-II, page 110
  10. function quicksort(data, left, right, less_than, i, last)
  11. {
  12. if (left >= right) # do nothing if array contains fewer
  13. return # than two elements
  14. quicksort_swap(data, left, int((left + right) / 2))
  15. last = left
  16. for (i = left + 1; i <= right; i++)
  17. if (@less_than(data[i], data[left]))
  18. quicksort_swap(data, ++last, i)
  19. quicksort_swap(data, left, last)
  20. quicksort(data, left, last - 1, less_than)
  21. quicksort(data, last + 1, right, less_than)
  22. }
  23. # quicksort_swap --- helper function for quicksort, should really be inline
  24. function quicksort_swap(data, i, j, temp)
  25. {
  26. temp = data[i]
  27. data[i] = data[j]
  28. data[j] = temp
  29. }