Google News
logo
Java Program for Selection Sorting
In the following examples of Java program for Selection Sorting :
Program :
public class SelectionSort {

    public static void main(String[] args) {
        int[] arr = {64, 25, 12, 22, 11};
        int n = arr.length;
        System.out.println("Original Array:");
        printArray(arr);

        for (int i = 0; i < n-1; i++) {
            int min_idx = i;
            for (int j = i+1; j < n; j++) {
                if (arr[j] < arr[min_idx]) {
                    min_idx = j;
                }
            }
            int temp = arr[min_idx];
            arr[min_idx] = arr[i];
            arr[i] = temp;
        }

        System.out.println("\nSorted Array:");
        printArray(arr);
    }

    public static void printArray(int[] arr) {
        for (int i = 0; i < arr.length; i++) {
            System.out.print(arr[i] + " ");
        }
        System.out.println();
    }
}
Output :
Original Array:64 25 12 22 11 
Sorted Array:11 12 22 25 64 
In this program, we first declare an integer array arr and initialize it with the values 64, 25, 12, 22, and 11. We also declare an integer variable n and initialize it with the length of the array. We then print the original array using a method called printArray.

Next, we use two nested loops to perform selection sort on the array. In the outer loop, we iterate through the array from the first element to the second-to-last element.

In the inner loop, we iterate through the remaining elements to find the index of the smallest element in the unsorted portion of the array. Once we find the index of the smallest element, we swap it with the first element of the unsorted portion.

Finally, we print the sorted array using the printArray method.