0

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;
   }
}
2
  • 1
    Are you sure that j <= size shouldn't be j < size? Commented Feb 13, 2020 at 18:26
  • 1
    You step outside the bounds of the array with for (j = i+1; j <= size; j++) { — it should be < not <=. Commented Feb 13, 2020 at 18:26

2 Answers 2

5
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.

Sign up to request clarification or add additional context in comments.

Comments

1

In the above lines of code I can see that you are using 0 based indexing for the array, hence when you are referring to Array[size] or Array[size+1] this throws garbage values, you should replace the inner loop to

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.