0

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;
}
0

You swapped < and >, if the middle element values[mid] is greater than value, you'd adjust end, if it's less than value, you'd adjust start. Also, there's no need for re-calculating mid there, you already calculate it at the start of the next iteration. And I cannot imagine any case that's neither equal, nor lower, nor higher than value. For floating point numbers, there's NaN (Not-a-Number), but not for integers.

You must log in to answer this question.

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