0

I understand my problem is with infinite loops but I would like some guidance on solving it. I am not sure if I should use a for - as I tried doing on comments - or if there is a better/more efficient approach. Comments on other problems on the code are also accepted. Thanks!

#include <cs50.h>

#include "helpers.h"


/**
* Returns true if value is in array of n values, else false.
*/

bool search(int value, int values[], int n)
{

// if input is less than 2, it doesn't form a pair
if (n < 0)
{
    return false;
}

// beggining and final portions
int min = 0;
int max = n -1;

// middle variable
int middle = n/2;

while (n > 0)
{

    // iterate over the values
    //for (int k = 0; k<(n-1); k++)   
   // {

   // }

    if (value > values[middle])
    {
        min = middle + 1;
    }

    else if (value < values[middle])
    {
        max = middle - 1;
    }

    else if (value == values[middle])
    {
        return true;
    }
}

 // if "needle" can't be found return false
return false;
}

/**
* Sorts array of n values.
*/
void sort(int values[], int n)
{
int min;
int swap;

for (int i = 0; i<(n-2); i++)
{
    min = i;

    // loop to find smallest element
    // check every value of j with the previous min (i)
    for (int j = 0; j<(n-1); j++)
    {
        if (values[j] < values[min])
        {
            min = j;
        }
    }

    // swap
    if (min !=i)
    {
        swap = values[i];
        values [i] = values[min];
        values[min] = swap;
    }

}
return;
}

1 Answer 1

0

Few recommendations:

  • Make clear for yourself what n is going to be when you call your functions. It = size from find.c, check there. You do so many "n-1" and "n-2", and I do not understand the logic behind.

  • Note that your sort does not sort. The only result of it is that the smallest element bubbles up. On the 1st iteration it indeed sends the smallest element in the beginning, but think what happens on the 2nd.

  • To step forward with search (remember redo your sort first), your code should take new min and max, determine new middle and repeat until either value[middle] = value (needle found) or min = max but no match (not found). You may do either by recursion, which is more stylish but more difficult perhaps, or with any kind of loop you are comfortable with.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .