# Selection Sort

• 05-06-2003
volk
Selection Sort
I'd greatly appreciate it if someone could explain for me exactly how the selection sort algorithm works.

Code:

```for (startScan = 0; startScan < (elems - 1); startScan++) {         minIndex = startScan;         minValue = array[startScan];         for (int index = startScan + 1; index < elems; index++)         {                 if (array[index] < minValue)                 {                         minValue = array[index];                         minIndex = index;                 }         }         array[minIndex]  = array[startScan];         array[startScan] = minValue; }```
The relationship between

Code:

```minIndex = startScan; minValue = array[startScan];```
and

Code:

```array[minIndex]  = array[startScan]; array[startScan] = minValue;```
is especially confusing me.
• 05-07-2003
PJYelton
It really is good practice for you to be able to work through this on your own, otherwise algorithms will always be confusing to you. I'd suggest taking a piece of paper, creating a random unsorted array like say {10,5,7,1,0,14,12,2} and working through the sort one line at a time keeping track of all of the variables. I guarantee that in only a couple of times through the loop you will understand exactly what those lines are doing, and you'll learn a heck of a lot more than by having someone explain it to you.
• 05-07-2003
Mister C
Use a deck of cards or some good visual aid. This is what I do.
• 05-08-2003
HybridM
Hi,

I'm a beginner too, and i also find it difficult to read through algorithms and find what they're doing easily, mind you...i've never really tried, so this seemed like a good piece of code.

So i sat down, pasted the algorithm into msvc, and commented it all out, and i must say i'm very satisfied with myself, i understand it all and not only that, can write my own selection sort with relative ease.

-Hybrid