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

时间:2017-07-04 09:36:18

标签: c arrays indices

我从以下链接

获得了c代码

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

我在上面的链接代码中添加了输入激励部分,并开发了以下c模型

#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]提供问题?

1 个答案:

答案 0 :(得分:0)

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

在排序时输出最新插入的值。您在进程中的某处获得输出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]]);
}

您需要做的是之后输出已排序的数组

// path config
requirejs.config({
  paths: {
    jquery: '//cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/core.js',
    tether: '//cdnjs.cloudflare.com/ajax/libs/tether/1.4.0/js/tether.min',
    bootstrap: '//cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.0.0-alpha.6/js/bootstrap.min',
  },
  shim: {
    bootstrap: {
      deps: ['jquery']
    }
  }
});

//async loading
requirejs(['tether'], function (Tether) {
  window.Tether = Tether;
  requirejs(['bootstrap']);
});

而且你会发现你的分类实际上是一种魅力......