Java - Selection Sort Algorithm

后端 未结 17 1649
我在风中等你
我在风中等你 2020-12-17 04:26

I have some questions about selection sort.I\'m a little bit confused.

 int [] arr = {5,4,3,2,1}; // This is my array
    int min = 0;

    for(int i = 0;i&l         


        
17条回答
  •  生来不讨喜
    2020-12-17 04:55

    You should start by assuming that the first element is the smallest one, then iterate over the array and if you find a smaller element, remember that position and assume that is the smallest one. When you get to the end of the array you should know the position of the smallest value. Switch that value with the value at the first position. Now the smallest value is first. Start at next position, assume that is the smallest value, iterate over the rest of the array... (I think you get the idea.

    Example:

    3,1,2
    

    Assume 3 (pos 1) is smallest. Compare with position 2, 1 < 3, so assume position 2 has smallest value. Compare with position 3, 3 < 1. Since we are at the end switch smallest with first position. (position 1 and 2)

    1,3,2
    

    Now, since position 1 is done, start with position 2. Assume 3 (position 2) is the smallest value. Compare with position 3 (2). 2 < 3, so assume position 3 has smallest value. Since we are at the end of the array we switch position 2 and 3

    1,2,3
    

    Done

提交回复
热议问题