Selection Sort Java Program
Selection sort is a kind of sorting mechanism where every element is compared with the every other element to sort the elements.
The following programs performs a selection sort on integers and also also calculates number of iteration required for sorting entire array. And also it simulates how the array is actually sorted on each iteration.
package sorting;
import java.util.Arrays;
public class SelectionSort {
public static void main(String[] rawInput) {
int numberOfIterations = 0;
int length = rawInput.length;
int input[] = new int[length];
for (int k = 0; k < length; k++) {
input[k] = Integer.parseInt(rawInput[k]);
}
System.out.println("Raw input" + Arrays.toString(input));
if (length == 0) {
System.out.println("Invalid input ");
} else {
for (int i = 0; i < length; i++) {
numberOfIterations++;
// iterate the rest of the array
for (int j = i; j input[j]) {
int temp = input[i];
input[i] = input[j];
input[j] = temp;
System.out.println(Arrays.toString(input));
}
}
}
}
System.out.println("after sorting" + Arrays.toString(input));
System.out.println("Total Number of iterations:" + numberOfIterations);
}
}
If we run the above program with following input,
Raw input[9, 8, 7, 6, 5, 4, 3, 2, 1, 0]
[8, 9, 7, 6, 5, 4, 3, 2, 1, 0]
[7, 9, 8, 6, 5, 4, 3, 2, 1, 0]
[6, 9, 8, 7, 5, 4, 3, 2, 1, 0]
[5, 9, 8, 7, 6, 4, 3, 2, 1, 0]
[4, 9, 8, 7, 6, 5, 3, 2, 1, 0]
[3, 9, 8, 7, 6, 5, 4, 2, 1, 0]
[2, 9, 8, 7, 6, 5, 4, 3, 1, 0]
[1, 9, 8, 7, 6, 5, 4, 3, 2, 0]
[0, 9, 8, 7, 6, 5, 4, 3, 2, 1]
[0, 8, 9, 7, 6, 5, 4, 3, 2, 1]
[0, 7, 9, 8, 6, 5, 4, 3, 2, 1]
[0, 6, 9, 8, 7, 5, 4, 3, 2, 1]
[0, 5, 9, 8, 7, 6, 4, 3, 2, 1]
[0, 4, 9, 8, 7, 6, 5, 3, 2, 1]
[0, 3, 9, 8, 7, 6, 5, 4, 2, 1]
[0, 2, 9, 8, 7, 6, 5, 4, 3, 1]
[0, 1, 9, 8, 7, 6, 5, 4, 3, 2]
[0, 1, 8, 9, 7, 6, 5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