title: Sort associative array with AWK
body: <p>Here's my array (gawk script) :</p>
  
  <pre><code>myArray["peter"] = 32
  myArray["bob"] = 5
  myArray["john"] = 463
  myArray["jack"] = 11
  </code></pre>
  
  <p>After sort, I need the following result :</p>
  
  <pre><code>bob    5
  jack   11
  peter  32
  john   463
  </code></pre>
  
  <p>When i use "asort", indices are lost. How to sort by array value without losing indices ? (I need ordered indices based on their values)</p>
  
  <p>(I need to obtain this result with awk/gawk only, not shell script, perl, etc)</p>
  
  <p>If my post isn't clear enough, here is an other post explaining the same issue : <a href="http://www.experts-exchange.com/Programming/Languages/Scripting/Shell/Q_26626841.html" rel="noreferrer">http://www.experts-exchange.com/Programming/Languages/Scripting/Shell/Q_26626841.html</a> )</p>
  
  <p>Thanks in advance</p>
  
  <p><strong>Update :</strong></p>
  
  <p>Thanks to you both, but i need to sort by values, not indices (i want ordered indices according to their values).</p>
  
  <p>In other terms, i need this result :</p>
  
  <pre><code>bob    5
  jack   11
  peter  32
  john   463
  </code></pre>
  
  <p>not :</p>
  
  <pre><code>bob 5
  jack 11
  john 463
  peter 32
  </code></pre>
  
  <p>(I agree, my example is confusing, the chosen values are pretty bad)</p>
  
  <p>From the code of Catcall, I wrote a quick implementation that works, but it's rather ugly (I concatenate keys &amp; values before sort and split during comparison). Here's what it looks like :</p>
  
  <pre><code>function qsort(A, left, right,   i, last) {
    if (left &gt;= right)
      return
    swap(A, left, left+int((right-left+1)*rand()))
    last = left
    for (i = left+1; i &lt;= right; i++)
      if (getPart(A[i], "value") &lt; getPart(A[left], "value"))
        swap(A, ++last, i)
    swap(A, left, last)
    qsort(A, left, last-1)
    qsort(A, last+1, right)
  }
  
  function swap(A, i, j,   t) {
    t = A[i]; A[i] = A[j]; A[j] = t
  }
  
  function getPart(str, part) {
    if (part == "key")
      return substr(str, 1, index(str, "#")-1)
    if (part == "value")
      return substr(str, index(str, "#")+1, length(str))+0
    return
  }
  
  BEGIN {  }
        {  }
  END {
  
    myArray["peter"] = 32
    myArray["bob"] = 5
    myArray["john"] = 463
    myArray["jack"] = 11
  
    for (key in myArray)
      sortvalues[j++] = key "#" myArray[key]
  
    qsort(sortvalues, 0, length(myArray));
  
    for (i = 1; i &lt;= length(myArray); i++)
      print getPart(sortvalues[i], "key"), getPart(sortvalues[i], "value")
  }
  </code></pre>
  
  <p>Of course I'm interested if you have something more clean...</p>
  
  <p>Thanks for your time</p>