Search code examples
csortingselection-sort

Selection Sort setting wrong values in C


New programmer here! I am implementing selection sort, with a max variable instead of the usual min, but I still want to sort from lowest to highest. The code below sorts the list perfectly except for the first value which it makes a very large negative number... Any tips for what I can fix to get it sorting properly?

void selection(int Array[], int size) {
   int i, j, max, temp;
   for (i = 0; i < size-1; i++) {
     max = i;
       for (j = i+1; j <= size; j++) {
          if ( Array[j] < Array[max] )
             max = j;
       }
       temp = Array[max];
       Array[max] = Array[i];
       Array[i] = temp;
   }
}

Solution

  • for(j = i+1; j<=size; j++)
    

    This line is your problem. You are accessing one past the end of the array, which will be undefined behavior and can often give you weird values. Change the condition to j < size.