0
#include <cs50.h>
#include <stdio.h>

#include "helpers.h"

//TODO binearysearch, om te controlere van de waarde.


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

{
    int left = 0;
    int right = n - 1;
    int midpoint = (right + left)/2;

    while (right >= left)
    {
        printf("%d - %d - %d\n", left, right, midpoint);
        if(values[midpoint] == value)
        {
          return true;
        }
        else if (values[midpoint] < value)
        {
            left = midpoint + 1;

        }
        else //if (values[midpoint] > value)
        {
            right = midpoint - 1;
        }
        midpoint = (right + left)/2;

    }
    return false;
}

//bubblesort, rangschikken van de waarde.

  void sort(int values[], int n)
{
    for (int i = 0; i < (n - 1); i++){
        for (int j = 0; j < n; j++){

        if (values[j + 1] < values[j])
        {
            int tm = values[j];
            values[j] = values[j+1];
            values[j+1] = tm;
        }
        }
        }
return;
}
0

Please don't just dump code here, at least describe the problems (and no, "check50 won't pass" is not the problem, unless same input used locally works).

If you printed your array before and after sorting, you might realise that some of the elements are not what you expect. In some cases, your code might exhibit other odd behaviour (maybe even the infamous "segmentation fault").

The reason is that index j in sort walks from 0 to n-1. Those are exactly the valid indices. But then you use values[j+1]. In case of j being n-1, this results in out-of-bounds access. Use j < n - 1 instead. If you want to skip the last values that are guaranteed to already be sorted, you could even use j < n - 1 - i.

Apart from this off-by-one, your code seems correct.

| improve this answer | |

You must log in to answer this question.

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