Sorting Arrays

#
# Like GNU awk's asort() but works with any awk(1)
# NB: Named _asort() to prevent conflict with GNU awk
#
function _asort(src, dest)
{
        k = nitems = 0
        for (i in src) dest[++nitems] = src[i]
        for (i = 1; i <= nitems; k = i++) {
                val = dest[i]
                while ((k > 0) && (dest[k] > val)) {
                        dest[k+1] = dest[k]; k--
                }
                dest[k+1] = val
        }
        return nitems
}

# Sample _asort() usage:
############################################################
#
#    string = "abc,123"
#    split(string, array, /,/)
#    n = _asort(array, sorted_array)
#    sorted_string = ""
#    for (i = 1; i <= n; i++)
#        sorted_string = sorted_string "," sorted_array[i]
#    sub(/^,/, "", sorted_string)
#    print sorted_string # produces "123,abc"
#
############################################################

#
# Like GNU awk's asorti() but works with any awk(1)
# NB: Named _asorti() to prevent conflict with GNU awk
#
function _asorti(src, dest)
{
        k = nitems = 0
        for (i in src) dest[++nitems] = i
        for (i = 1; i <= nitems; k = i++) {
                idx = dest[i]
                while ((k > 0) && (dest[k] > idx)) {
                        dest[k+1] = dest[k]; k--
                }
                dest[k+1] = idx
        }
        return nitems
}

# Sample _asorti() usage:
############################################################
#
#    foo["abc"] = 1 # value ignored
#    foo["123"] = 1 # value ignored
#    n = _asorti(foo, sorted_indices)
#    for (i = 1; i <= n; i++)
#        print sorted_indices[i]
#    # Output Produced:
#    #       123
#    #       abc
#
############################################################

Last updated