# Selection sort on the array $\{5,9,11,10,2\}$

I want to understand how the algorithm of selection sort sorts the given array, $$A[5]=\{5,9,11,10,2\}$$ Step -$$1:-$$ I compare A[0] with remaining elements of the array and since $$A[4] I swap them which leaves me with, $$A=\{2,9,11,10,5\}$$ Step-$$2:-$$ Repeating the similar procedure for $$A[1]$$ gives $$\{2,5,11,10,9 \}$$ Step-$$3:-$$ Repeating similar procedure gives $$\{2,5,10,11,9\}$$ And the for loop stops. But the array isn't sorted yet. Is there any mistake with my interpretation of the algorithm?

C program for selection sort:-

#include <stdio.h>

void selectionSort(int arr[], int n) {
int i, j, minIndex, temp;

for (i = 0; i < n - 1; i++) {
minIndex = i;
for (j = i + 1; j < n; j++) {
if (arr[j] < arr[minIndex]) {
minIndex = j;
}
}
if (minIndex != i) {
temp = arr[i];
arr[i] = arr[minIndex];
arr[minIndex] = temp;
}
}

• You should give the pseudocode of the algorithm that you are calling "selection sort" (because it is unclear with your description). Mar 18 at 17:32

You are stopping the i loop too soon.
You should try it again and keep track of the value of $$i$$ and keep in mind that in an array of length $$n$$, indices of the array are between $$0$$ and $$n-1$$.
• @mathboy i < n is unnecessary: the last loop with i = n - 1 does nothing, because the last element is necessary the greatest. Mar 19 at 8:52
• @greybeard you are right, of course. My point was that the loop invariant being "Elements at indices between 0 and $i-1$ are at the right position", it was not needed to do the last loop, because the element at index $n-1$, being the greatest, is at the right position. Mar 19 at 12:21