沒有QueryPerformanceFrequency(&frequency);
和QueryPerformanceCounter(&start);
函數,此代碼沒有問題。當我在順序搜索程序中使用這個函數的時候,它也可以工作。我無法弄清楚這裏有什麼問題。爲什麼我會出現分段錯誤?二進制搜索中的分割錯誤
#include <stdio.h>
#include <stdlib.h>
#include <windows.h>
int main()
{
LARGE_INTEGER frequency;
LARGE_INTEGER start;
LARGE_INTEGER end;
double interval;
int i, c, first, last, middle, n, search, array[20000];
FILE *fptr;
//read sorted list file!
if((fptr = fopen("sorted.txt","r"))==NULL){
printf("Error in reading file !\n");
return 0;
}
//array of sorted list!
while(!feof(fptr)){
if(!feof(fptr)){
fscanf(fptr,"%d",&array[i]);
i++;}
}
printf("Enter value to find\n");
scanf("%d",&search);
first = 0;
last = 20000 - 1;
middle = (first+last)/2;
QueryPerformanceFrequency(&frequency);
QueryPerformanceCounter(&start);
while(first <= last)
{
if (array[middle] < search)
first = middle + 1;
else if (array[middle] == search)
{
printf("%d found at location %d.\n", search, middle+1);
break;
}
else
last = middle - 1;
middle = (first + last)/2;
}
if (first > last)
printf("Not found! %d is not present in the list.\n", search);
QueryPerformanceCounter(&end);
interval = (double) (end.QuadPart - start.QuadPart)/frequency.QuadPart;
printf("%f\n", interval);
system("pause");
return 0;
}
而且一個邪惡的'#define LARGE_INTEGER char'和你的代碼壞了:P – 2013-03-30 17:16:04
你使用了一個調試器並試圖縮小這個問題嗎? –
這裏只是一個側面說明 - 你應該設置'last = i - 1',而不是'20000 - 1'。這當然假設'我<20000'。如果您使用20000,則正在搜索無效項目。 –