gpt4 book ai didi

c - 如果指定数字位于排序数组的末尾或开头,则二进制搜索函数无法找到它们

转载 作者:太空宇宙 更新时间:2023-11-04 03:20:39 26 4
gpt4 key购买 nike

正如上面的标题所说,我出于某种原因编写的二分查找函数无法找到给定的数字,如果它位于数组的末尾或开头。我曾尝试在调试器中寻找问题,但没有出现任何异常情况。

例如,如果您输入 24 25 26 27 28 而它试图查找的数字是 28,它将返回 false

但是如果数字是 24 25 28 26 30 它将返回 true

(假设这些数字已经预先排序)

bool search(int value, int values[], int n)
{
// check if only 1 item exists in values and if it is the item which is being looked for
if (n == 1)
{
if (value == values[0]) return true;
else return false;
}
int middle = n / 2;

// if the value is greater than middle, search the right half of the array
if (value > values[middle])
{
// initialize rightHalf since it is a variable length array
int rightHalf[n];
for(int x = 0; x <= n; x++) rightHalf[x] = 0;

int rightHalfSize = n - middle;

if (value > values[middle])
{
int rightHalfSize = n - middle - 1;
for (int i = 0, m = middle + 1; i < rightHalfSize; i++, m++)
{
rightHalf[i] = values[m];
}
}
return search(value, rightHalf, rightHalfSize);
} // if the value is less than middle, search the left half of the array
else if (value < values[middle])
{
// initialize leftHalf since it is a variable length array
int leftHalf[n];
for(int y = 0; y <= n; y++) leftHalf[y] = 0;

int leftHalfSize = n - middle;

for (int i = 0, m = 0; i < middle; i++, m++)
{
leftHalf[i] = values[m];
}
return search(value, leftHalf, leftHalfSize);
}
else if (value == values[middle]) return true;

return false;
}

最佳答案

目前尚不清楚在函数中创建一个可变长度数组的目的,该数组至少会由于循环而导致未定义的行为

int rightHalf[n];
for(int x = 0; x <= n; x++) rightHalf[x] = 0;

因为有人试图改变数组之外的内存,让 x 等于 n。

确定目标值是否存在的函数可以写得更简单。

例如

#include <stdio.h>
#include <stdbool.h>

bool search( const int a[], size_t n, int value )
{
if ( !n )
{
return false;
}
else
{
size_t middle = n / 2;
if ( a[middle] < value )
{
return search( a + middle + 1, n - middle - 1, value );
}
else if ( value < a[middle] )
{
return search( a, middle, value );
}
else
{
return true;
}
}
}

int main(void)
{
int a[] = { 24, 25, 26, 27, 28 };
const size_t N = sizeof( a ) / sizeof( *a );

printf( "a[0] - 1 is found - %d\n", search( a, N, a[0] - 1 ) );

for ( size_t i = 0; i < N; i++ )
{
printf( "a[%zu] is found - %d\n", i, search( a, N, a[i] ) );

}

printf( "a[%zu] + 1 is found - %d\n", N - 1, search( a, N, a[N-1] + 1 ) );

return 0;
}

程序输出为

a[0] - 1 is found - 0
a[0] is found - 1
a[1] is found - 1
a[2] is found - 1
a[3] is found - 1
a[4] is found - 1
a[4] + 1 is found - 0

关于c - 如果指定数字位于排序数组的末尾或开头,则二进制搜索函数无法找到它们,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46758185/

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