0

:( finds 42 in {39,40,41,42}

\ expected an exit code of 0, not 1

( it meaning I missing or have a return error??? )

 bool search(int value, int values[], int n)                           
  {// start of search code                                               
  // TODO: implement a searching algorithm
   if ( n <= 0)
    {
    return false;
    }
    //search for middle lists   if min = target 
   if (value == values[(n + 1) / 2])
    {
   return true;
    }
   //number greater search left
    if ( value > values[(n + 1)/ 2 ])
     {
     return search(value, &values[n / 2 + 1], n - n / 2 - 1);
     }  
    /number smaller search right 
   else if (value < values[(n + 1)/ 2 ])
    {
    return search( value, values, n/2);
    }
   return false;
}// end of search code                                                


 void sort(int values[], int n)                                            
{//start of selection sort code                                            


// TODO: implement a sorting algorithm (selection sort)
int min, swap;
for (int i = 0; i < n - 1; i++)
{
    min = i;
    for (int j = i + 1; j < n; j++)
    if (values[j] < values[min])
    min = j;

    //swap number
    if (min != i)
    {
        swap = values[i];
        values[i] = values[min];
        values[min] = swap;
    }
    return;
}    

}//End of selection sort

1 Answer 1

1

You are comparing to element values[(n+1)/2], but your recursive calls look like you meant values[n/2] instead, which makes a lot more sense, as n/2 is always the middle element's index, or the higher of the two middle elements' indices in case of even n. Imagine n being 1, an array of exactly one element. You'd access values[(1+1)/2], or values[1], which is clearly out of range (indices are 0-based, range from 0 to n-1).

In case of integers, numbers are always either equal, less than, or greater than, so you would not need that last if. Different for floating point, which knows a few special values like NAN (Not-a-Number, ironically stored in a number variable).

I don't see any error in your selection sort (better and more consistent indentation would have made code more readable, also, the editor has a {} button that'll add markdown to selected code).

1
  • Thank you. @Blauelf.
    – RedRabbit
    May 16, 2017 at 6:05

You must log in to answer this question.

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