Java Program to Implement Selection Sort

What is Selection Sort?

Selection sort is a sorting algorithm, specifically an in-place comparison sort. It has O(n2) time complexity, making it inefficient on large lists, and generally performs worse than the similar insertion sort. Selection sort in Java is noted for its simplicity and has performance advantages over more complicated algorithms in certain situations, particularly where auxiliary memory is limited.

Worst case performance : О(n2)
Best case performance : O(n2)
Average case performance : О(n2)

Selection Sort Algorithm:
selectionSort(array, size)
 repeat (size - 1) times
  set the first unsorted element as the min element
  for each unsorted element, if element is less than currentMin
       set the element as the newmin
 swap min with the first unsorted position
end selectionSort
Problem Solution

1. Starting from the beginning pick one number.
2. Compare it with others one by one.
3. Replace if the other number is lesser than this one.
4. Display the result.

Selection Sort Example:

If we have the array as {40,10,50,70,30}
and we apply selection sort to sort the array,
then the resultant array after each iteration will be as follows:

               Original array: {40, 10, 50, 70, 30}

Array after first  iteration         10  ->    40  ->    50  ->    70  ->    30
Array after second iteration         10  ->    30  ->    50  ->    70  ->    40
Array after third iteration          10  ->    30  ->    40  ->    70  ->    50
Array after fourth iteration         10  ->    30  ->    40  ->    50  ->    70
Array after fifth iteration          10  ->    30  ->    40  ->    50  ->    70
            
               Sorted array is  10  30  40  50  70
Program/Source Code

Here is source code of the Java Program to implement Selection Sort. The Java program is successfully compiled and run on a Windows system. The program output is also shown below.

advertisement
advertisement
  1. /*
  2.  * Java Program to Implement Selection Sort
  3.  */
  4.  
  5. import java.util.Scanner;
  6.  
  7. /* Class SelectionSort */
  8. public class SelectionSort 
  9. {
  10.     /* Selection Sort function */
  11.     public static void sort( int arr[] ){
  12.         int N = arr.length;
  13.         int i, j, pos, temp;
  14.         for (i = 0; i < N-1; i++)
  15.         {
  16.             pos = i;
  17.             for (j = i+1; j < N; j++)
  18.             {
  19.                 if (arr[j] < arr[pos])
  20.                 {
  21.                     pos = j;
  22.                 }
  23.             }
  24.             /* Swap arr[i] and arr[pos] */
  25.             temp = arr[i];
  26.             arr[i] = arr[pos];
  27.             arr[pos]= temp;            
  28.         }        
  29.     }
  30.     /* Main method */
  31.     public static void main(String[] args) 
  32.     {
  33.         Scanner scan = new Scanner( System.in );
  34.  
  35.         System.out.println("Selection Sort Test\n");
  36.         int n, i;
  37.         /* Accept number of elements */
  38.         System.out.println("Enter number of integer elements");
  39.         n = scan.nextInt();
  40.         /* Create integer array on n elements */
  41.         int arr[] = new int[ n ];
  42.         /* Accept elements */
  43.         System.out.println("\nEnter "+ n +" integer elements");
  44.         for (i = 0; i < n; i++)
  45.             arr[i] = scan.nextInt();
  46.         /* Call method sort */
  47.         sort(arr);
  48.         /* Print sorted Array */
  49.         System.out.println("\nElements after sorting ");        
  50.         for (i = 0; i < n; i++)
  51.             System.out.print(arr[i]+" ");            
  52.         System.out.println();            
  53.     }
  54.  
  55. }
Program Explanation:

1. The program defines a class named SelectionSort. Inside the class, there is a sort method that takes an integer array arr as its parameter.
2. The method begins by determining the length of the array N.
3. It uses nested loops to perform the selection sort:

  • The outer loop runs from i = 0 to N-2, as the last element will be in its correct position after the other elements are sorted.
  • For each i, it initializes pos as i.

4. The inner loop, with index j, runs from i+1 to N-1, comparing each element with the element at pos to find the smallest element.
5. If an element at index j is smaller than the element at pos, it updates pos to j.
6. After the inner loop completes, the program swaps the elements at arr[i] and arr[pos] to place the smallest element in its correct position at the beginning of the unsorted portion.
7. This process repeats until the entire array is sorted in ascending order.
8. In the main method, the program takes user input for the number of elements and the elements themselves.
9. It then calls the sort method (Selection sort algorithm) to sort the array and prints the sorted array to the console.

Sanfoundry Certification Contest of the Month is Live. 100+ Subjects. Participate Now!
Runtime Test Cases

Testcase 1: In this case, all sorted elements are entered in reverse order.

Selection Sort Test
 
Enter number of integer elements
20
 
Enter 20 integer elements
999 921 823 816 767 712 698 657 532 412 391 323 287 256 225 162 123 64 24 6
 
Elements after sorting
6 24 64 123 162 225 256 287 323 391 412 532 657 698 712 767 816 823 921 999

Testcase 2: In this case, we are entering all sorted elements.

advertisement
Selection Sort Test
 
Enter number of integer elements
20
 
Enter 20 integer elements
12 34 68 79 123 145 178 213 253 276 298 301 498 512 633 792 888 912 950 991
 
Elements after sorting
12 34 68 79 123 145 178 213 253 276 298 301 498 512 633 792 888 912 950 991

Testcase 3: In this case, we are entering all unsorted elements.

Selection Sort Test
 
Enter number of integer elements
20
 
Enter 20 integer elements
54 135 23 75 1 576 234 928 13 84 631 1283 748 124 54 6 24 485 1024 0
 
Elements after sorting
0 1 6 13 23 24 54 54 75 84 124 135 234 485 576 631 748 928 1024 1283

To practice programs on every topic in Java, please visit “Programming Examples in Java”, “Data Structures in Java” and “Algorithms in Java”.

advertisement

If you find any mistake above, kindly email to [email protected]

advertisement
advertisement
Subscribe to our Newsletters (Subject-wise). Participate in the Sanfoundry Certification contest to get free Certificate of Merit. Join our social networks below and stay updated with latest contests, videos, internships and jobs!

Youtube | Telegram | LinkedIn | Instagram | Facebook | Twitter | Pinterest
Manish Bhojasia - Founder & CTO at Sanfoundry
Manish Bhojasia, a technology veteran with 20+ years @ Cisco & Wipro, is Founder and CTO at Sanfoundry. He lives in Bangalore, and focuses on development of Linux Kernel, SAN Technologies, Advanced C, Data Structures & Alogrithms. Stay connected with him at LinkedIn.

Subscribe to his free Masterclasses at Youtube & discussions at Telegram SanfoundryClasses.