-1
import java.util.*;

public class SelectionSort {
    public static void main(String[] args) {

        int[] list = {10, 12, 4, 9, 1};
        int listLength = list.length;

        int minimum;
        int currentNum;
        int minIndex = 0;

        //prints list
        for (int count = 0; count < list.length; count++) {
            System.out.println(list[count]);
        }

        for (int counter = 0; counter < listLength-1; counter++) {
            minimum = list[counter];

            for (int index = counter; index < listLength; index++) {
                currentNum = list[index];

                if (minimum > currentNum) {
                    minimum = currentNum;

                    minIndex = index;
                }
            }

            list[minIndex] = list[counter];
            list[counter] = minimum;

            counter++;
        }

        System.out.println("\nReorganized List: \n");

        for (int count = 0; count < list.length; count++) {
            System.out.println(list[count]);
        }



    }
}

The codes outputs is 1,12,4,9,4. I have tried messing around with the length of the array when iterating through it in the for loops. The algorithm is supposed to organized the array in ascending order however I only managed to order the first smallest number then the algorithm breaks.

  • 2
    [What is a debugger and how can it help me diagnose problems?](https://stackoverflow.com/q/25385173/5221149) – Andreas Sep 16 '19 at 02:44
  • 3
    What happens when inner loop doesn't find anything and leaves `minIndex` unchanged? --- You're executing `counter++` **twice** for each iteration of the outer loop, because you have it at the end of the loop block, but also in the `for` loop itself. – Andreas Sep 16 '19 at 02:46

1 Answers1

0

You can use Arrays (java.util.Arrays). Please try the following.

int[] list = {10, 12, 4, 9, 1};
Arrays.sort(list);
for (int i = 0; i < list.length; i++) {
 System.out.println(list[i]);
};
Thiha Maung
  • 171
  • 2
  • 9