[英]storing n lowest numbers in a array C
我的問題是一個函數,我需要從我擁有的數據文件中計算出歐式距離,此后,我需要獲得由歐式距離給出的N個最低數字。
我制作的是一個數組,所有文件的長度都在1.000.000
左右,但是這給了我分段錯誤,這很明顯。 所以我想得到N值,創建一個N長度的數組,並存儲所有N個最低的值,然后按月牙順序對其進行排序,然后打印,但是我很難進行歐氏值之間的比較距離和存儲在數組中的距離。
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);
}
但是現在我需要將ed的N個最低值保存到dist [n],並且N由用戶指定
您可以像這樣存儲N個最低值
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;
}
}
如果N不是那么大,為什么不通過這個N數組進行FOR循環來檢查您的歐幾里得距離是否小於N數組的至少一個元素? 如果您對此有問題,則可能是因為您的數組未初始化。 這意味着您首先必須用大文件的前N個數字填充數組。 如果僅創建如下數組,則會發生這種情況:
int my_array[100];
如果未分配數組的所有100個值,則未分配的值將為0(可能取決於編譯器),並且可能導致比較問題。 到目前為止,只要我能理解您的問題就可以了。
如果要保存第N個最低數字,則必須執行以下偽代碼操作:
void calcDist(..)
{ ...
int array_size = //;
int number_add = -1;
for(int 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;
}
}
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.