# Finding the smallest value with Selection Sort

I think I'm stuck on finding the smallest value when employing Selection Sort.

Given an array of 7 values {4, 8, 1, 5, 3, 7, 9} , this is what I get (wrongly): {3,7,1,4,5,8,9}.

I understand perfectly why it does so but I can't get my head around on how to tell it to pick only the smallest value as the minimum (1 in this case). Here's a snippet of my code where I think I need to tackle this problem. Can someone offer a hint?

``````    int min = i; // i == 0 and so min == 4 as per the example above

for (int j = i + 1; j < size; j++)
{
if (haystack[j] < haystack[i])
{
min = j;
}
}
``````

## 1 Answer

so I assume that you have an outer `for` loop that iterates over the elements of the array where `i` is the index of an element.

you're trying to use `min` to keep track of the index of the minimum element in the array in each iteration. `min` correctly considers the `i`th element as the minimum element initially in each iteration, but what if `min` is set to `j` in any of the iterations? should you be still comparing `haystack[j]` with `haystack[i]` to determine the minimum element?

• What a silly mistake.. if (haystack[j] < haystack[min]). Thank you Kareem! – Alberto Apr 22 '16 at 5:48
• Kareem, I am feeling stupid now...not getting what you meant from " what if min is set to j in any of the iterations? should you be still comparing haystack[j] with haystack[i] to determine the minimum element?" – Imran Ahmed Mar 4 '18 at 20:32
• I tried so much to understand what min is doing here and why it is needed...but I am too stupid to go through that, Please, if you could write more elaborately to make me understand this – Imran Ahmed Mar 4 '18 at 20:37