0

in the last check of check50 when i entered these numbers and in that order 42 40 39 41 it gives me segmentation fault enter image description here

but when i put printf in my sort functions it runs normally enter image description here

so can someone please tell why is this happening

my search and sort codes :

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

      // TODO: implement a searching algorithm
      int min=0;
      int max = n;
    while(n > 0 && min <= max)
    {
        int mid = (min+max)/2;
        if (values[mid] == value)
        {
         return true;
        }
        else if(value > values[mid])
        {
          min = mid + 1;
        }
        else if(value < values[mid] )
        {
             max = mid -1;
        }
    }
    return false;
}

/**
 * Sorts array of n values.
 */ 

void sort(int values[], int n)
{ 

    // TODO: implement an O(n^2) sorting algorithm
    int counter = 1; 
    int store[n];
    while (counter != 0)
    {
        counter = 0;
        for(int y = 0 ; y < n ; y++)
        {
          for(int i = 0, j = 1 ; j < n - y ; i++, j++)
          {
                if(values[i] > values[j])
                {
                   printf("");   
                    store[n] = values[i];
                    values[i] = values[j];
                    values [j] = store[n];
                    counter++;
                }
          }
        }
    }
    return;
}
1
  • There's a code format button looking like {}. Select code, click it, and it'll indent the code by four spaces, which is Stack Exchange's markdown for code block. – Blauelf May 8 '17 at 8:22
0

The way you do search, initial value of max should be n-1, not n.

Imagine the case of n being 1, and the value searched for being larger than the single element, if you started with max at n, both min and max would end up as 1 after one iteration, and you'd access values[1], which probably does not exist for n being 1.

In sort, you declare an array store of length n (which means valid indices range from 0 to n-1), and then use store[n], which is outside of the valid range. Use a single integer instead, as you never need more than one.

1
  • thanks that solved it never thought of that !!! – Ali ElNaggar May 8 '17 at 8:53

You must log in to answer this question.

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