</>

Technology

Java Programs

Difficulty

Intermediate

Interview Question

Write a Java program to implement Selection Sort and Insertion Sort algorithms.

Answer

Selection Sort and Insertion Sort

Selection Sort

Java
import java.util.Arrays;

public class SelectionSort {
    public static void main(String[] args) {
        int arr[] = { 64, 25, 12, 22, 11 };

        System.out.println("Before: " + Arrays.toString(arr));

        int n = arr.length;

        for (int i = 0; i < n - 1; i++) {
            // Find minimum element in unsorted portion (i to n-1)
            int minIndex = i;
            for (int j = i + 1; j < n; j++) {
                if (arr[j] < arr[minIndex]) {
                    minIndex = j;
                }
            }

            // Swap minimum with first unsorted element
            int temp       = arr[minIndex];
            arr[minIndex]  = arr[i];
            arr[i]         = temp;
        }

        System.out.println("After:  " + Arrays.toString(arr));
    }
}

Output

CODE
Before: [64, 25, 12, 22, 11]
After:  [11, 12, 22, 25, 64]

How Selection Sort Works

CODE
Pass 1: min=11 at index 4 → swap with index 0 → [11, 25, 12, 22, 64]
Pass 2: min=12 at index 2 → swap with index 1 → [11, 12, 25, 22, 64]
Pass 3: min=22 at index 3 → swap with index 2 → [11, 12, 22, 25, 64]
Pass 4: min=25 at index 3 → already in place  → [11, 12, 22, 25, 64]

Insertion Sort

Java
public class InsertionSort {
    public static void main(String[] args) {
        int arr[] = { 12, 11, 13, 5, 6 };

        System.out.println("Before: " + Arrays.toString(arr));

        int n = arr.length;

        for (int i = 1; i < n; i++) {
            int key = arr[i];  // element to be inserted
            int j   = i - 1;

            // Shift elements greater than key one position right
            while (j >= 0 && arr[j] > key) {
                arr[j + 1] = arr[j];
                j--;
            }
            arr[j + 1] = key;  // insert key at correct position
        }

        System.out.println("After:  " + Arrays.toString(arr));
    }
}

Output

CODE
Before: [12, 11, 13, 5, 6]
After:  [5, 6, 11, 12, 13]

How Insertion Sort Works

CODE
i=1: key=11, shift 12 right → [11, 12, 13, 5, 6]
i=2: key=13, 12<13 no shift → [11, 12, 13, 5, 6]
i=3: key=5,  shift 13,12,11 → [5, 11, 12, 13, 6]
i=4: key=6,  shift 13,12,11 → [5, 6, 11, 12, 13]

Sorting Algorithms Comparison

AlgorithmBestAverageWorstSpaceStable
Bubble SortO(n)O(n²)O(n²)O(1)Yes
Selection SortO(n²)O(n²)O(n²)O(1)No
Insertion SortO(n)O(n²)O(n²)O(1)Yes
Merge SortO(n log n)O(n log n)O(n log n)O(n)Yes
Quick SortO(n log n)O(n log n)O(n²)O(log n)No
Arrays.sort()O(n log n)O(n log n)O(n log n)O(n)Yes

Follow AutomateQA