Selection Sort

Write a program to sort an array using selection sort.

import java.io.*;
import java.util.*;
public class Main {
    public static void main (String [] args) {
        // Scanner sc = new Scanner (System.in);
        // int n = sc.nextInt();
        // int arr [] = new int[n];
        int arr[] = {1,5,2,4,8,3};
        int n = 6;
        // for(int i=0;i<n;i++) {
        //     arr[i] = sc.nextInt();
        // }
        selectionSort(arr , n);
    }
    private static void selectionSort(int arr[] ,int n) {
        for (int i=0;i<n-1;i++) {
            int min = i;
            for(int j=i+1;j<n;j++) {
                
                if(arr[j]<arr[min]){
                    int temp = arr[min];
                    arr[min] = arr[j];
                    arr[j] = temp;
                }
            }
            
        }
        for (int i=0;i<n;i++) {
            System.out.print(arr[i] + " ");
        }
    }
}

Leave a Reply

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