I have been trying to solve Pset3 search and sort - looked at all possible online forums but I cannot solve it.
Please help. Where am I going wrong? Is my binary search OK? What about my bubble sort? I feel like they are both wrong... This is what I get when I check the results:
:) helpers.c exists
:) helpers.c compiles
:( finds 42 in {42,43,44}
\ expected an exit code of 0, not 1
:) 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}
PLEASE HELP ME..
Here's my code:
/**
* helpers.c
*
* Helper functions for Problem Set 3.
*/
#include <cs50.h>
#include "helpers.h"
bool search(int value, int values[], int n)
{
int start = 0;
int end = (n-1);
int mid;
if (n < 0)
{
return false;
}
while (start <= end)
{
mid = (start+end)/2;
if (values[mid]==value)
{
return true;
}
else if (values[mid]<value)
{
end=(mid-1);
mid=(start+end)/2;
}
else if (values[mid]>value)
{
start=(mid+1);
mid=(start+end)/2;
}
else
break;
}
return false;
}
void sort(int values[], int n)
{
int swap;
for (int i = 0; i < (n-1); i++)
{
for (int j = 0; i < j-1-i; j++)
if (values[j] > values[j+1])
{
swap=values[j+1];
values[j+1]=values[j];
values[j]=swap;
}
}
return;
}