How to Implement Selection Sort in Java


In this example we will show how to implement selection sort in Java.

Source Code

package com.beginner.examples;

import java.util.Arrays;

public class SelectionSortExample {

    public static void main(String[] args) {

        int[] arr = {10,34,235,22,1,93};

        sort(arr);

        System.out.println(Arrays.toString(arr));

    }

    private static void sort(int[] arr) {

        int l = arr.length;

        for (int i = 0; i < l - 1; i++) 
        {
            int min = i;
            for (int j = i + 1; j < l; j++) 
            {
                if (arr[j] < arr[min]) 
                {
                    min = j;
                }
            }

            int temp = arr[i];
            arr[i] = arr[min];
            arr[min] = temp;
        }

    }

}

Output:

[1, 10, 22, 34, 93, 235]

References

Imported packages in Java documentation:

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments