# Select Sort code not working

I am trying to sort the array below using Selection Sort procedure:

``````array [] = {5,4,3,2,1}
``````

However, when I run the code it sort the array as 12222. It clearly stops sorting after 2. I suspect the problem is where I am trying to swap values but not sure what I am doing wrong. Please help!

``````for (int i = 0; i < n-1; i++)
{
int smallest = values [i];
int position = i;

for (int j = i + 1; j < n; j++)
{
if (values [j] < smallest)
smallest = values [j];
position = j;
}

int tmp = values [i];
values [i] = smallest;
values [position] = tmp;
}
``````

## 2 Answers

I would use a tool like gdb to debug this. Here is a question that should hopefully give you a hint for how you can fix this

What do you think happens when `values[j] < smallest` is true and what do you think happens when it's false? Can you prove what you think happens?

Thanks Kareem for your help!

I was missing curly braces after if statement:

for (int j = i + 1; j < n; j++)

``````    {
if (values [j] < smallest)
{
smallest = values [j];
position = j;
}
}
``````