Advertisement
devinteske

Array Sorting Algorithms for non-GNU awk(1)

Oct 14th, 2014
879
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Awk 1.77 KB | None | 0 0
  1. #
  2. # Like GNU awk's asort() but works with any awk(1)
  3. # NB: Named _asort() to prevent conflict with GNU awk
  4. #
  5. function _asort(src, dest,        k, nitems, i, val)
  6. {
  7.         k = nitems = 0
  8.         for (i in src) dest[++nitems] = src[i]
  9.         for (i = 1; i <= nitems; k = i++) {
  10.                 val = dest[i]
  11.                 while ((k > 0) && (dest[k] > val)) {
  12.                         dest[k+1] = dest[k]; k--
  13.                 }
  14.                 dest[k+1] = val
  15.         }
  16.         return nitems
  17. }
  18.  
  19. # Sample _asort() usage:
  20. ############################################################
  21. #
  22. #   string = "abc,123"
  23. #   split(string, array, /,/)
  24. #   n = _asort(array, sorted_array)
  25. #   sorted_string = ""
  26. #   for (i = 1; i <= n; i++)
  27. #       sorted_string = sorted_string "," sorted_array[i]
  28. #   sub(/^,/, "", sorted_string)
  29. #   print sorted_string # produces "123,abc"
  30. #
  31. ############################################################
  32.  
  33. #
  34. # Like GNU awk's asorti() but works with any awk(1)
  35. # NB: Named _asorti() to prevent conflict with GNU awk
  36. #
  37. function _asorti(src, dest,        k, nitems, i, idx)
  38. {
  39.         k = nitems = 0
  40.         for (i in src) dest[++nitems] = i
  41.         for (i = 1; i <= nitems; k = i++) {
  42.                 idx = dest[i]
  43.                 while ((k > 0) && (dest[k] > idx)) {
  44.                         dest[k+1] = dest[k]; k--
  45.                 }
  46.                 dest[k+1] = idx
  47.         }
  48.         return nitems
  49. }
  50.  
  51. # Sample _asorti() usage:
  52. ############################################################
  53. #
  54. #   foo["abc"] = 1 # value ignored
  55. #   foo["123"] = 1 # value ignored
  56. #   n = _asorti(foo, sorted_indices)
  57. #   for (i = 1; i <= n; i++)
  58. #       print sorted_indices[i]
  59. #   # Output Produced:
  60. #   #       123
  61. #   #       abc
  62. #
  63. ############################################################
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement