Marcus
Marcus

Reputation: 75

How to loop through Selection Sort in Java?

I want to show each iteration of the selection sort to print out how it works, how would I loop and print this? I have it printing out the output after its been sorting already. Here's my code:

public class TestSelectionSort {

    public static void main(String[] args) {

        int list[] = { 2, 56, 34, 25, 73, 46, 89, 10, 5, 16 };

        selectionSort(list, list.length);

        System.out.println("After sorting, the list elements are:");

        for (int i = 0; i < list.length; i++) {
            System.out.print(list[i] + " ");
        }

    }

    public static void selectionSort(int[] list, int listLength) {
        int index;
        int smallestIndex;
        int minIndex;
        int temp;

        for (index = 0; index < listLength - 1; index++) {
            //Step a
            smallestIndex = index;

            for (minIndex = index + 1; minIndex < listLength; minIndex++)
                if (list[minIndex] < list[smallestIndex])
                    smallestIndex = minIndex;

            //Step b
            temp = list[smallestIndex];
            list[smallestIndex] = list[index];
            list[index] = temp;

        }

    }
}

Upvotes: 2

Views: 659

Answers (2)

Sachin Gupta
Sachin Gupta

Reputation: 8378

You can do this by adding a print statement at the end of your outer loop of selection sort. E.g. :

public static void selectionSort(int[] list, int listLength) {
        int index;
        int smallestIndex;
        int minIndex;
        int temp;

        for (index = 0; index < listLength - 1; index++) {
            //Step a
            smallestIndex = index;

            for (minIndex = index + 1; minIndex < listLength; minIndex++)
                if (list[minIndex] < list[smallestIndex])
                    smallestIndex = minIndex;

            //Step b
            temp = list[smallestIndex];
            list[smallestIndex] = list[index];
            list[index] = temp;

            System.out.println("Printing data for iteration no " + index);
            printData(list);

        }

    }

    private static void printData(int[] list) {
        for (int i = 0; i < list.length; i++) {
            System.out.print(list[i] + " ");
        }

        System.out.println();
    }

Upvotes: 2

timrau
timrau

Reputation: 23058

Just copy the snippet you used for printing final result:

for(int i = 0; i < list.length; i++)
{
    System.out.print(list[i] + " ");
}

before the end of the loop in selectionSort().

Upvotes: 1

Related Questions