Sunday 23 July 2017

Selection Sort

import java.util.*;
public class SelectionSort {
Scanner scan=new Scanner(System.in);
public static void selectionSort(int[] arr)
{
        for (int i = 0; i < arr.length - 1; i++)
        {
            int index = i;
            for (int j = i + 1; j < arr.length; j++){
                if (arr[j] < arr[index]){
                    index = j;
                }
            }
            int smallerNumber = arr[index];  
            arr[index] = arr[i];
            arr[i] = smallerNumber;
        }
    }
     
    public static void main(String a[]){
        int[] arr1 = {11,32,3,18,98,43,9,65};
        System.out.println("Before Selection Sort");
        for(int i:arr1){
            System.out.print(i+" ");
        }
        System.out.println();
         
        selectionSort(arr1);//sorting array using selection sort
       
        System.out.println("After Selection Sort");
        for(int i:arr1){
            System.out.print(i+" ");
        }
    }
}



OUTPUT:
Before Selection Sort
11 32 3 18 98 43 9 65
After Selection Sort

3 9 11 18 32 43 65 98

No comments:

Post a Comment