» » » Implementation of selection sort algorithm in java with Example program

  • Selection sort algorithm is to arrange unsorted elements in to sorting order with increasing or decreasing order.
  • To sort list of  unsorted list of elements first it will search for minimum value in the list and place it in first index.

  • Now first place is fixed with smallest value in the list now it starts from second element and compare next element and if it is big it compares next element if it is small it picks that element and compares with next element.
  • So again it picks smallest element in the list and place it in second place. This procedure will repeat until it reaches n-1 position.

Time complexity of selection sort algorithm: 


1.Best case  time complexity:     O(n2)
2.Average case time complexity: O (n2)
3.Worst case time complexity:     O (n2)


Program #1:  Write a  Java example program to sort unsorted elements in ascending order using selection sort algorithm

  1. package com.java.sortingalgorithms;

  2. public class SelectionSortInJava {

  3. public static int[] selectionSortArray(int[] array){
  4.         
  5. for (int i = 0; i < array.length - 1; i++)
  6. {
  7.            int index = i;

  8.   for (int j = i + 1; j < array.length; j++)

  9.                if (array[j] < array[index])
  10.                    index = j;
  11.      
  12.            int minimumNumber = array[index]; 
  13.            array[index] = array[i];
  14.            array[i] = minimumNumber;

  15. }
  16.        return array;
  17.  }
  18.      
  19. public static void main(String a[]){
  20.          
  21.  int[] array = {12,24,6,56,3,9,15,41};
  22.         
  23.    System.out.println("Before sorting");
  24.        
  25.     for(int i:array){
  26.   System.out.print(i);
  27.   System.out.print(", ");
  28.    }
  29.  
  30.    int[] resultarr = selectionSortArray(array);
  31.        
  32.        System.out.println("\nAfter sorting"); 

  33.       for(int i:resultarr){

  34.     System.out.print(i);
  35.     System.out.print(", ");
  36.      }
  37. }
  38. }

Output:

  1. Before sorting
  2. 12, 24, 6, 56, 3, 9, 15, 41, 
  3. After sorting
  4. 3, 6, 9, 12, 15, 24, 41, 56,

Implementation of Selection Sort algorithm

selection sort in java example program

Instance Of Java

We will help you in learning.Please leave your comments and suggestions in comment section. if you any doubts please use search box provided right side. Search there for answers thank you.
«
Next
Newer Post
»
Previous
Older Post

No comments

Leave a Reply

Select Menu