Have been solving pset3 'Find' problem for a week now. My code seems fine to me, but apparently, it is not. When I input './generate 1000 50 | ./find 127' into command line it says: 'Didn't find needle in haystack'. Can't figure out what is the problem. Any help would be appreciated. TIA.
Also, when I run check it returns this:
:) helpers.c exists
:) helpers.c compiles
:) finds 42 in {42,43,44}
:) finds 42 in {41,42,43}
:( finds 42 in {40,41,42}
\ expected an exit code of 0, not 1
:) finds 42 in {41,42,43,44}
:( finds 42 in {40,41,42,43}
\ expected an exit code of 0, not 1
:( finds 42 in {39,40,41,42}
\ expected an exit code of 0, not 1
:) doesn't find 42 in {39,40,41}
:) doesn't find 42 in {39,40,41,43}
:) finds 42 in {42,40,39,41}
Does this mean that sort and search are working fine but there is some problem with returning 0 and 1?
Here is my code:
bool search(int value, int values[], int n)
{
//return false if n is non-positive
if (n < 0) {
return false;
};
//define start and end of our search horizon
int start = 0;
int end = n-1;
//iterate through the array and implementing binary search
while (start<=end) {
//define middle index and value of element at that middleIndex
int middleIndex = (start + end)/2;
int middleValue = values[middleIndex];
//returning true if value is equal to middleValue
if(value == middleValue) {
return true;
}
//if value is higher, then changing end of our array to the left side of middle index
else if(value > middleValue) {
end = middleIndex - 1;
}
//if value is lower, then changing start of array to the right side of middle index
else if(value < middleValue) {
end = middleIndex - 1;
}
};
return false;
}
void sort(int values[], int n)
{
//pointer variable
int temp;
//iterating through numbers of array till the n-1 element
for(int i = 0; i < n - 2; i++)
{
//defining smallest value as an i
int smallest = values[i];
//iterating through numbers of array starting with the i + 1 till the last one to find the smallest value
for(int j = i+1; j < n - 1; j++) {
//if the next value is smaller than the previous value, then this value becomes the smallest
if(values[j] < values[smallest]) {
smallest = values[j];
}
}
//swapping elements using pointer
temp = smallest;
smallest = values[i];
values[i] = temp;
}
return;
}