Selection Sort Source Code in Java

In this source code example, we will write a Java program to demonstrate how to implement the Selection Sort algorithm in Java.

Selection sort is a simple sorting algorithm that works by repeatedly selecting the smallest element from the unsorted portion of the list and placing it at the end of the sorted portion of the list.

Selection Sort Source Code in Java

public class SelectionSort {

   public void printArray(int[] arr) {
      int n = arr.length;
      for (int i = 0; i < n; i++) {
         System.out.print(arr[i] + " ");
      }
      System.out.println();
   }

   public void sort(int[] arr) {
      int n = arr.length;
      for (int i = 0; i < n - 1; i++) {
         int min = i;
         for (int j = i + 1; j < n; j++) {
            if (arr[j] < arr[min]) {
               min = j;
            }
         }
         int temp = arr[min];
         arr[min] = arr[i];
         arr[i] = temp;
      }
   }

   public static void main(String[] args) {
      int[] arr = new int[] { 5, 1, 2, 9, 10 };
      SelectionSort ss = new SelectionSort();
      ss.printArray(arr);
      ss.sort(arr);
      ss.printArray(arr);
   }
}

Output:

5 1 2 9 10 
1 2 5 9 10
Selection sort has a time complexity of O(n^2), making it less efficient than other sorting algorithms for large lists. However, it is simple to implement and can be useful for small lists or as a reference implementation.

Comments