Skip to content

Selection Sort

My selection sort implementation

import java.util.Random;

public class SelectionSort {

    // Method to perform selection sort
    public static void selectionSort(int[] arr) {
        for (int i = 0; i < arr.length - 1; i++) {
            int minIndex = i;
            for (int j = i + 1; j < arr.length; j++) {
                if (arr[j] < arr[minIndex]) {
                    minIndex = j;
                }
            }

            // Swap the found minimum element with the first element
            int temp = arr[minIndex];
            arr[minIndex] = arr[i];
            arr[i] = temp;
        }
    }

    public static void main(String[] args) {
        Random generator = new Random();
        int[] list = new int[10];
        
        for (int i = 0; i < list.length; i++) {
            list[i] = generator.nextInt(1000);
        }

        // Call the selectionSort method
        selectionSort(list);

        // Print the sorted array
        for (int i : list) {
            System.out.println(i + "\t");
        }
    }
}

Oh hi there 👋 It’s nice to meet you.

Sign up to receive awesome content in your inbox, every month.

We don’t spam!

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.