I am sorting and passing the sorted Array to SEARCH. sort is working in debugger but not in check50
:) helpers.c exists.
:) helpers.c compiles.
:( sorts {5,4,3,2,1}
expected "2", not "\n"
:( sorts {5,3,1,2,4,6}
expected "3", not "\n4\n6\n"
:) finds 28 in {28,29,30}
:) finds 28 in {27,28,29}
:) finds 28 in {26,27,28}
:) finds 28 in {27,28,29,30}
:) finds 28 in {26,27,28,29}
:) finds 28 in {25,26,27,28}
:) doesn't find 28 in {25,26,27}
:) doesn't find 28 in {25,26,27,29}
:) doesn't find 28 in {29,30,31,32}
:) doesn't find 28 in {29, 30, 31}
:) finds 28 in {30,27,28,26}
and here's my code
/** * helpers.c * * Helper functions for Problem Set 3. */
#include <cs50.h>
#include <stdio.h>
#include "helpers.h"
// maximum amount of hay
int sortedstack[65536] = {0};
int indexstack[65536] = {0};
/**
* Returns true if value is in array of n values, else false.
*/
bool search(int value, int values[], int n)
{
// TODO: implement a searching algorithm
//while length >0
if(n > 0 )
{
int k = n/2;
int mid = sortedstack[k];
if (mid == value)
{
return true;
}
else if(mid < value )
{
if ( n % 2 == 0)
{
for(int g = 1; g < k; g++)
{
sortedstack[g-1] = sortedstack[k +g];
}
return (search(value, sortedstack, k));
}
else
{
for(int g = 0; g < k; g++)
{
sortedstack[g] = sortedstack[k+1];
}
return (search(value, sortedstack, k));
}
}
else if(mid > value )
{
//move left
for(int g = 0; g < k; g++)
{
sortedstack[g] = sortedstack[g];
}
return (search(value, sortedstack, k));
}
else
{
return false;
}
}
else
{
return false;
}
}
/**
* Sorts array of n values.
*/
void sort(int values[], int n)
{
int z;
// TODO: implement a sorting algorithm
for (int i = 0; i < n; i++)
{
int j = values[i];
indexstack[j]++;
}
int t =0;
for(z =0; z < n; z++)
{
for (; t < 65536; t++)
{
int l = indexstack[t];
if (l > 0)
{
for(int y =0; y < l; y++)
{
sortedstack[z] = t;
z = z + 1;
}
z = z -1;
t = t + 1;
break;
}
}
}
return;
}