views:

245

answers:

2

Hi all, I have an associative array in awk that gets populated like this...

chr_count[$3]++

When I try to print my chr_counts I use this:

for (i in chr_count) {
    print i,":",chr_count[i];
}

But not surprisingly, the order of i is not sorted in any way. Is there an easy way to iterate over the sorted "keys" of chr_count?

A: 

This is taken directly from the documentation:

 populate the array data
 # copy indices
 j = 1
 for (i in data) {
     ind[j] = i    # index value becomes element value
     j++
 }
 n = asort(ind)    # index values are now sorted
 for (i = 1; i <= n; i++) {
     do something with ind[i]           Work with sorted indices directly
     ...
     do something with data[ind[i]]     Access original array via sorted indices
 }
Jefromi
+3  A: 

Instead of asort, use asorti(source, destination) which sorts the indices into a new array and you won't have to copy the array.

Then you can use the destination array as pointers into the source array.

Dennis Williamson
Wow, totally forgot about that despite reading right past it in the docs. This is definitely the better answer.
Jefromi