gpt4 book ai didi

c - 为什么我在比较线性搜索和二分搜索时每次都得到零?

转载 作者:行者123 更新时间:2023-11-30 19:24:44 25 4
gpt4 key购买 nike

我想找到通过线性和二分搜索在数组中查找元素所花费的时间。我已经传递了变量n,它接受一个整数,并且它不断地将其值减少1到0。我想获得用于比较线性和二分搜索的总时间表图表,即从数组大小1到任何大数字。但对于每种情况,我都获得了 0.000000 时间。

我的目标是绘制当 (x) 即输入大小为 0 到任何大数时这两种搜索所花费的时间。

#include<stdio.h>
#include<stdlib.h>
#include<time.h>

long int lin_search(long int [], long int, long int );
long int bin_Search(long int [], long int, long int, long int);
void merge(long int [], long int, long int, long int );
void mergeSort(long int [], long int, long int);

long int main()
{
long int n, *arr, x;
clock_t start, end;
FILE *fp;
double lin_time , bin_time ;

//Destination file: "search_comp.txt"
fp = fopen("search_comp.txt", "a");

printf("\nEnter total no of inputs:\t");
scanf("%ld", &n);
printf("\n::::::::::::::::::::::::::::\n");
while (n--)
{
arr = (long int *)malloc(n * sizeof(long int));
for (long int i = 0; i < n; i++)
{
arr[i] = rand() % n;
}

mergeSort(arr, 0, n - 1);
x = rand() % n;
//Linear search time..
start = clock();
long int res1 = lin_search(arr, n, x);
end = clock();
lin_time = (double)(end - start) / (double)(CLOCKS_PER_SEC);

//Binary search time ...
start = clock();
long int res2 = bin_Search(arr, 0, n - 1, x);
end = clock();
bin_time = (double)(end - start) / (double)(CLOCKS_PER_SEC);

//File creation data taking input........
fprintf(fp, "%ld;%lf;%lf;%ld;%ld\n", n, lin_time, bin_time, res1, res2);
free(arr);
}

printf("\nTask Completed!\n");
fclose(fp);
return 0;
}

long int lin_search(long int arr[],long int n,long int x)
{
long int i;
for (i = 0; i < n; i++)
{
if (arr[i] == x)
{
return i;
}
}
return -1;
}

long int bin_Search(long int arr[],long int l,long int r,long int x)
{
while (l <= r)
{
long int m = l + (r - l) / 2;

if (arr[m] == x)
return m;

if (arr[m] < x)
l = m + 1;

else
r = m - 1;
}
return -1;
}

void merge(long int arr[],long int l,long int m,long int r)
{
long int i, j, k;
long int n1 = m - l + 1;
long int n2 = r - m;

long int L[n1], R[n2];

for (i = 0; i < n1; i++)
L[i] = arr[l + i];
for (j = 0; j < n2; j++)
R[j] = arr[m + 1 + j];


i = 0;
j = 0;
k = l;
while (i < n1 && j < n2)
{
if (L[i] <= R[j])
{
arr[k] = L[i];
i++;
}
else
{
arr[k] = R[j];
j++;
}
k++;
}

while (i < n1)
{
arr[k] = L[i];
i++;
k++;
}

while (j < n2)
{
arr[k] = R[j];
j++;
k++;
}
}

void mergeSort(long int arr[],long int l,long int r)
{
if (l < r)
{

long int m = l + (r - l) / 2;

mergeSort(arr, l, m);
mergeSort(arr, m + 1, r);
merge(arr, l, m, r);
}
}

Error message from the system for large value of n

此外,如果我省略 while 循环(最多 100,000 个),程序就可以正常工作,即

while(n--)
{
:::::
:::::
:::::
}
printf("\nTask Completed!\n");
fclose(fp);
return 0;

对于较高的 n 值,程序不会显示我的任务已完成!消息。

最佳答案

避免除以 0 或取模

//while (n--) {
for ( ; n; n--) {
...
x = rand() % n;

关于c - 为什么我在比较线性搜索和二分搜索时每次都得到零?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59908168/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com