Selection Sort Using Java

This is a simple program to illustrate how to use selection sort for sorting integers using java code.
Selection sort is an in-place sorting technique with time complexity of O(n2).
Its time complexity remains same in all the 3 cases (i.e. best, average and worst) .This type of sorting is preferred where memory is limited.

Screenshots:



Program:
import java.util.*;
class Sorting
{
     public static void selectionSort(int arr[], int size)
      { 
                int i, j, pos=0,temp=0;
                for(i=0;i<size-1;i++)
               {
                     pos=i;
                     for (j = i+1; j < size; j++)
                     {
                           if (arr[j] < arr[pos])
                           pos = j;
                     }
                     // Swapping the elements
                     temp = arr[i];
                     arr[i] = arr[pos];
                     arr[pos]= temp;            
               }          
       }
 
     public static void main(String[]  args)
     {
              int n=0;
              Scanner s=new Scanner(System.in);
              System.out.println("\n How many numbers:");
              n=s.nextInt();
              int[] arr=new int[n];
              System.out.println("Enter the numbers");

              for(int i=0;i<n;i++)
              {
                          arr[i]=s.nextInt(); 
              }
              selectionSort(arr, n);     //calling the sorting function
              System.out.println("the sorted array :");
              for(int j=0;j<n;j++)
              {
                          System.out.print("\t"+arr[j]);//printing the sorted array 

              }
   }

}

Found helpful, Please Share !

Comments

Popular posts from this blog

Non Restoring Division Algorithm Implementation in C

Bit Stuffing Code Implementation in Java

Hackerrank Modified Kaprekar Numbers Solution