In: Computer Science
Create a Java Application that implements a Selection sort algorithm to sort an array of 20 unsorted numbers. You should initiate this array yourself and first output the array in its original order, then output the array after it has been sorted by the selection sort algorithm.
Code:
public class Main {
public static void selectionSort(int[] arr) {
for (int i = 0; i < arr.length - 1; i++) {
int index = i;
for (int j = i + 1; j < arr.length; j++) {
if (arr[j] < arr[index]) {
index = j;// searching for lowest index
}
}
int smallerNumber = arr[index];
arr[index] = arr[i];
arr[i] = smallerNumber;
}
}
public static void main(String a[]) {
int[] arr1 = { 19, 55, 45, 90, 8, 3, 57, 66, 14, 3, 2, 43, 11, 58, 22, 12, 23, 14, 67, 99 };
System.out.println("Before sorting:");
for (int i : arr1) {
System.out.print(i + " ");
}
System.out.println();
selectionSort(arr1);// sorting array using selection sort
System.out.println("After performing selection sort:");
for (int i : arr1) {
System.out.print(i + " ");
}
System.out.println();//newline
}
}
Output:
Code screenshot: