Thursday, 2 June 2016

Selection Sort (Java program)

Selection Sort: In this sorting algorithm, we first find the smallest element in an array of numbers and swap it with the first element. Then we find the second smallest element and swap it with the second element and so on until the complete list of numbers is sorted.
The following program is for sorting in Increasing order a list of elements.
package Javanew;

Program:

import java.util.*;
public class SelectionSort {
    public static void main(String args[]){
    System.out.println("Enter the number of elements :");
    Scanner obj=new Scanner(System.in);
    int n=obj.nextInt();
    int a[]=new int[n];
    System.out.println("Enter "+n+" elements :");
    for(int i=0;i<n;i++){
        a[i]=obj.nextInt();
    }
    int count=0;
    while(count<n){
        int z=findMin(a, count, (n-1));
        int k=a[count];
        a[count]=a[z];
        a[z]=k;
        count++;
    }
    System.out.println("Sorted array is : ");
    for(int i=0;i<n;i++){
        System.out.print(a[i]+"\t");
    }
    }
 
    static int findMin(int a[], int start, int end){
        int min=a[start];
        int loc=start;
            for(int i=start;i<end;i++){
                if (a[i+1]<min)
                {
                    min=a[i+1];
                    loc=i+1;
                }
     
            }
        return loc;
    }
}

Order of Growth & Running times:

Since the major part is played by the findMin(function), which does the comparison of (end-start) number of terms.
That is during first iteration there were n-1 comparisons, followed by n-2 comparisons in second iteration and so on.
so, f(n)= (n-1) + (n-2) + (n-3) +- - -+ 2 + 1 = n(n-1)/2 = O(n2) (For Worst and Average case)