Search code examples
javaarrayssortingselection-sort

My selection sorting code is failing on one index


I'm having great issues with my selection sort code can anyone explain to me where i'm going wrong?

this code works for the most part however when it gets to the 4/5th round it false to sort the 5 as the next lowest instead going to the 6 in the array.

this is what my output looks like. As you can see the 5 is clearly in the wrong place.

any help understand why this is would be great thank you.

[1, 9, 4, 10, 5, 3, 6, 2, 8, 7]
[1, 2, 9, 10, 5, 3, 6, 4, 8, 7]
[1, 2, 3, 10, 9, 5, 6, 4, 8, 7]
[1, 2, 3, 4, 10, 9, 5, 6, 8, 7]
[1, 2, 3, 4, 6, 10, 9, 5, 8, 7]
[1, 2, 3, 4, 6, 5, 10, 9, 8, 7]
[1, 2, 3, 4, 6, 5, 7, 10, 9, 8]
[1, 2, 3, 4, 6, 5, 7, 8, 10, 9]
[1, 2, 3, 4, 6, 5, 7, 8, 9, 10]

-

public class Selection {
    void findSmallestNumberIndex(int[] numbers, int index) {
        //int[] numbers = {4, 9, 2, 10, 5, 3, 6, 1, 8, 7};

        int n = numbers.length;
        int min_idx = index; //4

        for (int j = index + 1; j < n; j++) {
            if (numbers[j] < numbers[min_idx]) {
                min_idx = j;
            }

            int temp = numbers[min_idx];
            numbers[min_idx] = numbers[index];
            numbers[index] = temp;
        }
    }

    public static void main(String[] args) {
        int[] numbers = {4,9,2,10,5,3,6,1,8,7};
        int NumLen = numbers.length;
        int[] sortedNum = new int[NumLen];
        int index;
        index = 0;
        Selection OB = new Selection();

        do {
            OB.findSmallestNumberIndex(numbers, index);
            index++;
            System.out.println(Arrays.toString(numbers));
        } while (index != (NumLen - 1));
    }
}

Solution

  • Move the logic to adjust array outside the for loop, here's how it should look:

     void findSmallestNumberIndex(int[] numbers, int index) {
    
      //int[] numbers = {4, 9, 2, 10, 5, 3, 6, 1, 8, 7};
    
      int n = numbers.length;
      int min_idx = index; //4
    
      for (int j = index + 1; j < n; j++) {
       if (numbers[j] < numbers[min_idx]) {
        min_idx = j;
       }
    
      }
      int temp = numbers[min_idx];
      numbers[min_idx] = numbers[index];
      numbers[index] = temp;
     }