0

Hi I am very frustrated since 5 days that I cannot pass check50 that keeps giving me error as: Does anyone have any suggestions?

:) helpers.c exists.
:) helpers.c compiles.
:( sorts {5,4,3,2,1}
    expected "3", not "\n"
:( sorts {5,3,1,2,4,6}
    expected "3", not "\n4\n6\n"
:( finds 28 in {28,29,30}
    expected exit code 0, not 1
:) finds 28 in {27,28,29}
:( finds 28 in {26,27,28}
    expected exit code 0, not 1
:) finds 28 in {27,28,29,30}
:) finds 28 in {26,27,28,29}
:( finds 28 in {25,26,27,28}
    expected exit code 0, not 1
:) 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}----------
bool search(int value, int values[], int n)
{
 //binary search
    //1. case if mid value is equal value is found
    //2. if mid value is less than ignore left move right
    //3. if mid value is bigger than ignore right and move left

    if(n < 0){
        return false;
    }
    int left = 0;
    int right = n-1;

    while(right >= left){
        int mid = (left + right)/2;
        if(value == values[mid]){
            return mid;
        }else if(value  < values[mid]){
            left = mid +1 ;
        }else {
            right = mid - 1;
        }
    }
return false;


}

/**
 * Sorts array of n values.
 */
void sort(int values[], int n)
{
    for(int i = 0; i < n; i++){
        for(int k = 0; k < n-1-i; k++){
            if(values[i] > values[k+1]){
                int tem = values[k + 1];
                values[k+1] = values[i];
                values[i] = tem;
            }
        }
    }
return;
}

1 Answer 1

0

In search, you confused value < values[mid] and value > values[mid].

Also, search should return true, not mid, on finding the value.

In sort, you seem to attempt a bubble sort. In bubble sort, you compare adjacent elements values[k] and values[k+1], no i involved in the comparison/swapping part.

2
  • thanks for the help. what do you mean by confused in value < values[mid] and value > values[mid]. can you elaborate and I have changed the code but still got ' expected exit code 0, not 1' this error
    – NTM
    Nov 8, 2017 at 8:01
  • If value < values[mid], you need to search the lower half (right = mid - 1;), while for value > values[mid], you need to search the upper half (left = mid + 1;).
    – Blauelf
    Nov 8, 2017 at 8:49

You must log in to answer this question.

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