2017-07-04 16 views
0

我得到的C代碼從下面的鏈接如何獲得的陣列的頂部N個值的索引用C

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

我已經加入輸入激勵部到上述鏈接代碼並開發下面的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]問題?

+0

我建議你要想想你將如何達到你想要達到的目標,並基於在此檢查,程序是否在做你想要的。複製一些你不明白的代碼並不會幫助你學習... – Betlista

+0

除了Betlista的評論,學習如何使用調試器並檢查變量的內容,這些變量在你程序中的變化將會是有益的。 – Toby

+2

作爲一個方面說明,如果你要從代碼初始化數組,那麼你可以使它成爲一個普通的數組而不是堆分配(即'const double arr [] = {0.00623,0.745,... };')。 – unwind

回答

0

這僅僅是輸出的問題......

你輸出你的latestly插入值權而尚未排序。你在你的進程中取得的輸出top[2] = 2地方,但後來,你通過插入新的價值前移位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]]); 
} 

,你會看到你的排序實際工作的魅力。

相關問題