Selection sorting algorithm

This is a discussion on Selection sorting algorithm within the C++ Programming forums, part of the General Programming Boards category; Selection sort scans an array of ints to find the smallest, then replaces the first element with the smallest. When(if) ...

Selection sorting algorithm

Selection sort scans an array of ints to find the smallest, then replaces the first element with the smallest. When(if) that happens, the routine continues again but this time excluding the first element(which is now the smallest), and so on.

Since you initially set small to the value at array[loc], then you should have initially set locsmall to loc. When I did that with your original code, the data was sorted correctly.

The first algorithm was: Look at all values after the passed in location and find the smallest remaining value. Then, swap the current location with the smallest remaining that was just found. Recurse on the next location. I don't know if that's selection sort, but it works.

The new algorithm is: For each element after the current location, if that element is smaller, immediately swap it and then recursively sort the rest of the array. The problem with that is that after two positions have been compared, its possible that different values can get swapped into the positions that are no longer in the correct order (I believe that is what is happening here). Here are the swaps I get for your new code:

Notice how in the fourth row, the third spot (6) is now less than the fourth spot (748). Later, 5 gets moved into the fourth spot, but the algorithm has already compared the third and fourth spots and so it assumes they are still in order, leaving the 5 after the 6 in the array.