Selection Sort Algorithm | Java Programs

Output:

*** Selection Sort Algorithm ***

--- Array Before ---
98, 32, 21, 26, 77, 7, 8, 421, 

--- Array After ---
7, 8, 21, 26, 32, 77, 98, 421,

Click Here For Java Online Compiler

Solution:

/**
 *
 * @author Alee Ahmed Kolachi
 */
public class SelectionSort {

    public static int[] sortMethod(int[] array) {

        for (int i = 0; i < array.length - 1; i++) {
            int index = i;
            for (int j = i + 1; j < array.length; j++) {
                if (array[j] < array[index]) {
                    index = j;
                }
            }

            int smaller = array[index];
            array[index] = array[i];
            array[i] = smaller;
        }
        return array;
    }

    public static void main(String a[]) {

        int[] array1 = {98, 32, 21, 26, 77, 7, 8, 421};

        System.out.println("*** Selection Sort Algorithm ***" + "\n");
        System.out.println("--- Array Before ---");
        for (int i = 0; i < array1.length; i++) {
            System.out.print(array1[i] + ", ");

        }
        System.out.println("\n");
        System.out.println("--- Array After ---");

        int[] array2 = sortMethod(array1);
        for (int i = 0; i < array2.length; i++) {
            System.out.print(array2[i]);
            System.out.print(", ");
        }
    }
}
Share This :

Related Post



sentiment_satisfied Emoticon