# Selection Sort

 Rehman . · August 15, 2015 Anybody want's to talk about selection sort ?why do we have ``for (int i = 0; i < n-2; i++)``this n-2 thingy ?

## Replies

 Sha Kal · August 16, 2015 No, you put i <= n-2 or i < n-1; Rich Sharma · August 18, 2015 i am not sure where you learned selection sort in that form from, but selection sort process is selecting the minumum value from a list of objects at a certain position. for example, you would want to first select the smallest element of the entire array, then switch it with the first element, find the smallest object after the minumum, or second smallest, and switch it with the second element, and so on. so what you would do and need is nested for loops, one controlling array accesses from every certain index 0, 1, 2 .. array.length - 1 second loop is finding the smallest value, setting the index = i + 1 since you want to search starting from the that index. anyway, for the loop i would say i < n - 1 because once you go to the last element, it is already in place. like sha kal said, you could have read it wrong or got it from someone who did not write it correctly. that way, you never know if the last two elements are sorted right by doing i < n-2 so you would put <=. Dol Lod · August 18, 2015 @Rich, good explanation, but it has far too many details.Here's the main idea of selectioin sort in a nutshell:Find the smallest element in the array and swap it with the first element in the array.Now move on to the next position in the array and repeat until all elements are in order form smallest to biggest.Abstract the swap function.So it looks like this.int min;for(int outer=0;outer
• 1

## C

120,720 followers