Pset 3 (2017): create program, find, that finds a number in an array of generated numbers. We need to implement functions for both sorting and searching the array using helper files. Since a binary search is being used we have to sort the array first in numerical order before we can search.
I feel like I have correctly implemented the bubble sort, as when I ran the sort function in a separate file of it's own it properly sorted through an array an ordered it.
However when I try to execute using the PSET guidelines and the same sort function I run into some problems, leading me to believe the sort isn't working right.
For easier testing, I have a nums.txt file that contains {25, 20, 15, 10, 5, 2, 1}.
./find 2 < nums.txt gives me "Didn't find needle in haystack"
./find 25 < nums.txt gives me "Found needle in haystack"
debug50 ./find 2 < nums.txt and trying to debug doesn't work for me either, so I can't get to one step my code.
Does anybody have any insight on how I can get the right output when using ./find or even how I can fix debugging to get a clearer idea of the problem? Here is the helper.c file.
#include <cs50.h>
#include "helpers.h"
bool search(int value, int values[], int n)
{
// is array filled?
if (n <= 0)
{
return false;
}
int start = 0;
int end = n - 1;
int mid = (start + end) / 2;
// iterate through each value within array
while (start <= end)
{
if (values[mid] == value)
{
return true;
}
if (values[mid] << value)
{
start = mid + 1;
mid = (start + end) / 2;
}
else if (values[mid] >> value)
{
end = mid - 1;
mid = (start + end) / 2;
}
}
return false;
}
void sort(int values[], int n)
{
int temp;
int i, j;
int swapcount = 0;
for (i = 0; i < n - 1; i++)
{
for (j = 0; j < n - 1 - i; j++)
{
if (values[j] > values[j+1])
{
temp = values[j];
values[j] = values[j+1];
values[j+1] = temp;
swapcount = swapcount + 1;
}
}
if (swapcount == 0)
{
break;
}
}
}
sort
code looks fine (move theswapcode = 0;
into the outer loop to make better use of it), what aboutsearch
? For "printf debugging", you could print the array to the console before and after sorting to make sure it does that correctly. Compiling withmake
I hope?