2012-11-08 55 views
1

我的問題是有一個函數,我需要從數據文件中計算歐幾里德距離,之後我需要得到歐幾里德距離給出的N個最小數字。在一個數組中存儲n個最小數字C

我所做的是一個數組,其長度爲1.000.000左右的所有文件,但它給了我分段錯誤,這是顯而易見的。所以我認爲是得到N值,創建一個N長度的數組,然後將N中最低的一個存儲起來,然後按新月順序排序,然後打印出來,但是iam難以比較歐幾里得的值距離和存儲在陣列中的距離。

void calcDist(Nodo *L,int vpesq[],int n) 
{ 
    int dist[n],ed; 
    while(L!=NULL){ 
    x=0; 
    for(i=0;i<12;i++) 
      x=x+pow((vpesq[i]-L->caracter[i]),2); 
      ed=sqrt(x); 
} 

,但現在我需要保存版的N個最低值DIST [N]而N是用戶給定

+2

的N個最低值,請發表一些代碼片段。除了描述之外,我們沒有任何工作。 – Grambot

回答

1

你可以存儲這樣

void store_lowest_N(int* array, int N, int new_value) { 
    for (int i=0; i<N; i++) { 
     if (new_value < array[i]) { 
      for (j=N-1; j>i; j--) { 
       array[j] = array[j-1]; // shift the larger values down to make space 
      } 
      array[i] = new_value; 
      break; 
     } 
    } 
} 

void initialize_array(int* array, int N) { 
    for (int i=0; i<N; i++) { 
     array[i] = INT_MAX; 
    } 
} 
+0

謝謝你是這樣的:D –

0

如果N本來就不大,所以通過不作FOR循環這個N陣列檢查你的歐幾里得距離是否小於N陣列中的至少一個元素? 如果你有這個問題,那麼這可能會導致你的數組未被初始化。這意味着你首先必須用你的大文件的前N個數字來填充數組。出現這種情況,如果你只讓一個這樣的數組:

int my_array[100]; 

如果不指定數組中的所有100個值,非asigned值將值0(可能取決於編譯器),並可能導致你與你比較的問題。 這是所有,如果我理解你的問題到目前爲止。

+0

多數民衆贊成那不是問題,我的問題是浪費資源的方式,我有我使用長整型數組[1000000],我認爲它可以做到而不浪費所有這一切 –

0

如果你想保存的N個降低數量,你必須做的是這樣的僞代碼:

void calcDist(..) 
    {int i; 
    int array_size = //; 
    int number_add = -1; 

for(i = 0; i < number_of_numbers_to_read; i++) 
{ 
    x = // calculate euclidean distance 

    if(number_add < array_size) // Theres still space in the array 
    { 
    number_add++;     // a new number in the array 
    } 
    // rearrange the array so it will be order again 
    for(j = 0; j <= number_add; j++) 
    { 
     if(array_lower[j] > x) // This is the position to put the value 
     { 
      aux = array_lower[j]; // if have to swap than 
      array_lower[j] = x; 
      x = aux; 
     } 
    } 
    } 

} 
相關問題