title: How to get indices of top N values of an array in C
body: <p>I got the c-code from following link </p>
  
  <p><a href="https://stackoverflow.com/questions/25459043/how-to-get-the-indices-of-top-n-values-of-an-array">How to get the indices of top N values of an array?</a></p>
  
  <p>I have added input stimulus part to the above link code and developed the following c-model</p>
  
  <pre><code>#include &lt;stdio.h&gt;
  #include &lt;stdlib.h&gt;
  #include &lt;string.h&gt;
  #include &lt;math.h&gt;
  int main() {
    double *arr =malloc(sizeof(double)*10);
    int N=10;
    int n =5;
    int *top =malloc(sizeof(int)*10);
    arr[0] = 0.00623; 
    arr[1] = 0.745;
    arr[2] = 0.440;
    arr[3] = 0.145;
    arr[4] = 0.645;
    arr[5] = 0.741;
    arr[6] = 0.542;
    arr[7] = 0.445;
    arr[8] = 0.146;
    arr[9] = 0.095;
    top[0] = 100;
    top[1] = 100;
    top[2] = 100;
    top[3] = 100;
    top[4] = 100;
    int top_count = 0;
    int i;
    for (i=0;i&lt;N;++i) {
  
      // invariant: arr[top[0]] &gt;= arr[top[1]] &gt;= .... &gt;= arr[top[top_count-1]]
      // are the indices of the top_count larger values in arr[0],...,arr[i-1]
      // top_count = max(i,n);
      int k;
  
      for (k=top_count;k&gt;0 &amp;&amp; arr[i]&gt;arr[top[k-1]];k--){
  
      }
      // i should be inserted in position k
  
      if (k&gt;=n) continue; // element arr[i] is not in the top n
      // shift elements from k to top_count
      int j=top_count;
      if (j&gt;n-1) { // top array is already full
        j=n-1;
  
      } else { // increase top array
        top_count++;
      }
  
      for (;j&gt;k;j--) {
        top[j]=top[j-1];
      }
      // insert i
      top[k] = i;
      printf("top[%0d] = %0d\n",k,top[k]);
  
  
    }
    return top_count;
  }
  </code></pre>
  
  <p>After executing the code, I am getting following output</p>
  
  <pre><code>top[0] = 0
  top[0] = 1
  top[1] = 2
  top[2] = 3
  top[1] = 4
  top[1] = 5
  top[3] = 6
  top[4] = 7
  </code></pre>
  
  <p>The index is wrong for <code>top[2]</code>. It should be <code>top[2] =4</code>. I am not able to decode why it is giving problem for only <code>top[2]</code>?</p>