これは、edX.org の CS50 コースの PSET 3 です。
私はこの一連の問題に非常に長い間苦労してきました。特に、binarySearch 関数が機能しません。セグメンテーション違反が発生し続け、対処方法がわかりません。私はこれについて考えるのに多くの時間を費やしましたが、それがわかりません。
これが私のコードです。誰かがここで斜めになっているところを概念的に指摘できますか? ありがとう。
#include <stdio.h>
#include <cs50.h>
bool binarySearch(int value, int values[], int min, int max)
{
bool answer = false;
if (max < min)
{
answer = false;
}
else if (values[max] == value)
{
answer = true;
}
else if (values[min] == value)
{
answer = true;
}
else
{
int midPoint = (max + min) / 2;
if (values[midPoint] == value)
{
answer = true;
}
else if (values[midPoint] > value)
{
answer = binarySearch(value, values, min, midPoint);
}
else
{
answer = binarySearch(value, values, midPoint, max);
}
}
return answer;
}
int main (int argc, char *argv[])
{
int value = 34;
int values[] = {11,22,33,44,55,66,77,88,99,1010};
int max = sizeof(values) / sizeof(int);
if (binarySearch(value, values, 0, max - 1))
{
printf("Found needle!\n");
}
else
{
printf("Did not find needle\n");
}
}
検索している値が配列にない場合、セグメンテーション違反が発生し続けます。