如何在 C 中获取数组的前 N ​​个值的索引

How to get indices of top N values of an array in C

我从以下 link

获得了 C 代码

How to get the indices of top N values of an array?

我在上面的 link 代码中添加了输入激励部分,并开发了以下 c-model

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
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<N;++i) {

    // invariant: arr[top[0]] >= arr[top[1]] >= .... >= 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>0 && arr[i]>arr[top[k-1]];k--){

    }
    // i should be inserted in position k

    if (k>=n) continue; // element arr[i] is not in the top n
    // shift elements from k to top_count
    int j=top_count;
    if (j>n-1) { // top array is already full
      j=n-1;

    } else { // increase top array
      top_count++;
    }

    for (;j>k;j--) {
      top[j]=top[j-1];
    }
    // insert i
    top[k] = i;
    printf("top[%0d] = %0d\n",k,top[k]);


  }
  return top_count;
}

执行代码后,我得到以下输出

top[0] = 0
top[0] = 1
top[1] = 2
top[2] = 3
top[1] = 4
top[1] = 5
top[3] = 6
top[4] = 7

top[2] 的索引错误。应该是top[2] =4。我无法解码为什么它只给 top[2]?

带来问题

这只是一个输出问题...

您在排序时立即输出最新插入的值。您在流程的某处获得输出 top[2] = 2,但稍后,您通过插入新值 before:

将 2 移出数组
for (;j > k; j--)
{
    top[j] = top[j-1]; // moves the 2 out with further iterations!
}

你要做的就是输出排序后的数组之后:

} // for (i = 0; i < N; ++i)

// sorting finished now, so NOW output:

for (i = 0; i < n; ++i)
{
    printf("top[%0d] = %0d (%f)\n", i, top[i], arr[top[i]]);
}

你会发现你的排序真的很有魅力...