0

I've tried using "./generate 1000 50 | ./find 127" and it doesn't find a needle so I guess my code is wrong. I'm not sure if it is my search function or sort function or both that are wrong. Here's a link to the code as well: https://gist.github.com/9121ea9a4e8ce516b0e7fee9614e3ca1

bool search(int value, int values[], int n)
{
    // TODO: implement a searching algorithm
    int i = 0;
    while(n>0)
    {
        //look at the middle of list
        int m=round(n+i)/2;
        //if number found, return true
        if(value==values[m])
        {
            return true;
        }
        //if number higher, search right
        if(value>values[m] && value<values[n])
        {
            i=m+1;
        }
        //if number lower, search left
        if(value>values[i] && value<values[m])
        {
            n=m-1;
        }
    }
    return false;
}

void sort(int values[], int n)
{
    // TODO: implement an O(n^2) sorting algorithm
    for(int i=0; i<n; i++)
    {
        for(int j=i+1; j<n+1; j++)
        {
            if(values[j]<values[i])
            {
                values[i]=values[j];
            }
        }
    }
}
4
  • I don't see the value 'n' being initialized anywhere in your code. Perhaps fix that? Commented Aug 14, 2016 at 18:52
  • @NullityNull n is passed as a parameter.
    – ChrisG
    Commented Aug 14, 2016 at 18:56
  • @ChrisG not in the search function Commented Aug 14, 2016 at 20:07
  • I'm pretty sure that the third parameter in search() is int n.
    – ChrisG
    Commented Aug 15, 2016 at 13:29

1 Answer 1

1

OK, first your sort() is definitely wrong.

By saying values[i]=values[j], doesn't mean that those two values are exchanged, so now both values[i] and values[j] have the value that values[j] had.

Take a closer look at how bubble sort works at Wikipedia.

Your search() on the other hand, is mostly correct from what I can see, except three places.

  1. If n is the length of the array, values[n] is out of range, because the numbering starts from 0. (if length is 3 for example, the indexes are 0, 1, 2. You can't get values[3].)
  2. You don't have to use the round() function. (int + int) / int == int, because / means integer division, that is it doesn't give you the remainder.
  3. You probably don't have to check if the value is greater/lower than the first/last values in the array.

You must log in to answer this question.

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