why do we have

`for (int i = 0; i < n-2; i++)`

this

**n-2**thingy ?

## Selection Sort |

## Post a Reply |

## Replies |
Oldest Newest Rating |

0 |
Sha Kal
· August 16, 2015
No, you put
i <= n-2 or i < n-1; |

0 |
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 <=. |

0 |
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<array.length;outer++) { min=outer; for(int inner=outer+1;inner<array.length;inner++) { if(array[inner]<array[min]) min=inner; } swap(array[outer],array[min]); } |

0 |
Rehman .
· August 18, 2015
Thanks guys yea that person must have wrote it wrong, i learned it from:
https://study.cs50.net/selection_sort and you can see as well that they made a condition n-2 how every i have done it with n-1 and its running perfectly fine |

0 |
Sha Kal
· August 18, 2015
i < n - 1 is equal to i < = n - 2. Thats why they are putting in pseudo code n to -2. |

- 1