Selection Sort Program in Java (ICSE Class 10 Board Pattern)

⚡ Direct Answer & Key Takeaway

Selection Sort divides an array into a growing sorted prefix on the left and an unsorted suffix on the right. In each outer pass `i` from `0` to `n-2`, it scans indices `i+1` through `n-1` to locate the index `minIdx` of the smallest element (for ascending) or largest element (for descending), then performs a single swap between `arr[i]` and `arr[minIdx]`. Thus, Selection Sort executes at most `n-1` swaps total.

1. Why Selection Sort Tracks Index minIdx Before Swapping

Students often confuse Selection Sort with an unoptimized double-loop exchange that swaps inside the inner loop whenever `arr[j] < arr[i]`. True Selection Sort avoids repeated intermediate writes by storing only the position `minIdx = i` before the inner loop begins. As `j` scans from `i + 1` to `n - 1`, any element smaller than `arr[minIdx]` simply updates `minIdx = j`. Only after the inner loop finishes scanning the entire unsorted suffix does the outer loop swap `arr[i]` with `arr[minIdx]`. If `minIdx != i`, three lines perform the exchange; otherwise the element is already sitting in its rightful home. This single-swap-per-pass design makes Selection Sort noticeably gentler on memory writes than Bubble Sort.

  • Initialize `minIdx = i` at the start of every outer pass, not `minIdx = 0`.
  • Compare `arr[j] < arr[minIdx]` (not `arr[j] < arr[i]`) so you always track the smallest value found so far.
  • Place the swap block outside the inner `j` loop and inside the outer `i` loop.
  • For descending order, rename or keep `maxIdx` and flip the test to `arr[j] > arr[maxIdx]`.

2. Tracing {64, 25, 12, 22, 11} Pass by Pass

Let us dry run Selection Sort in ascending order on `{64, 25, 12, 22, 11}` (`n = 5`). In Pass 0 (`i = 0`), `minIdx` starts at `0` (`64`), updates to `1` (`25`), `2` (`12`), and finally `4` (`11`); swapping `arr[0]` and `arr[4]` gives `{11, 25, 12, 22, 64}`. In Pass 1 (`i = 1`), scanning `25, 12, 22, 64` finds `12` at index `2`, swapping indices `1` and `2` to yield `{11, 12, 25, 22, 64}`. Pass 2 (`i = 2`) scans `25, 22, 64`, finds `22` at index `3`, and swaps to `{11, 12, 22, 25, 64}`. Pass 3 (`i = 3`) compares `25` and `64`, leaves `minIdx = 3`, and completes sorting.

  • Notice how the sorted boundary grows from the left (`index 0 -> 1 -> 2 -> 3`), opposite to Bubble Sort.
  • Total comparisons remain `4 + 3 + 2 + 1 = 10`, regardless of whether the array starts sorted or reversed.
  • Only 3 swaps occurred across the entire run (`(64,11)`, `(25,12)`, `(25,22)`), saving writes on large datasets.

3. ICSE Board Questions That Test Selection Sort

In recent CISCE specimen and board papers, Selection Sort regularly appears in Section B with domain twists: sorting 10 double weights in descending order, arranging 15 integer pin codes in ascending order, or sorting student roll numbers alongside marks. Unlike Bubble Sort, Selection Sort can also sort characters (`char[]`), decimals (`double[]`), or strings (`String[]` using `arr[j].compareTo(arr[minIdx]) < 0`) with the exact same `minIdx` pattern. Examiners specifically verify whether your inner loop starts at `i + 1` and whether swapping happens after the inner loop terminates. Including `if (minIdx != i)` shows clean defensive coding without changing output.

  • When sorting `double` values (heights, prices, weights), declare `double temp;` instead of `int temp;`.
  • In Section A, count passes carefully: after `k` passes of Selection Sort, the leftmost `k` elements are guaranteed final.
  • Keep `minIdx` clearly listed in your Variable Description Table as 'Index of smallest element in unsorted part'.

4. SelectionSortICSE.java (Minimum-Index Selection Sort)

import java.util.*;

public class SelectionSortICSE {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);

        System.out.print("Enter array size: ");
        int n = sc.nextInt();
        int[] arr = new int[n];

        System.out.println("Enter " + n + " integers:");
        for (int i = 0; i < n; i++) {
            arr[i] = sc.nextInt();
        }

        for (int i = 0; i < n - 1; i++) {
            int minIdx = i;
            for (int j = i + 1; j < n; j++) {
                if (arr[j] < arr[minIdx]) {
                    minIdx = j;
                }
            }
            if (minIdx != i) {
                int temp = arr[i];
                arr[i] = arr[minIdx];
                arr[minIdx] = temp;
            }
        }

        System.out.print("Ascending Sorted Array: ");
        for (int i = 0; i < n; i++) {
            System.out.print(arr[i] + " ");
        }
        System.out.println();
        sc.close();
    }
}

Verified Console / Dry-Run Output:

Enter array size: 5
Enter 5 integers:
64 25 12 22 11
Ascending Sorted Array: 11 12 22 25 64

5. CISCE Variable Description Table (VDT) & Dry Run

VariableData TypeExam Purpose & Sample Value
nintTotal number of integers in the array (Sample: 5)
arr[]int[]Stores unsorted elements and final sorted list (Sample: {64, 25, 12, 22, 11})
iintOuter loop index marking start of unsorted subarray (Sample: 0 to 3)
jintInner loop index scanning elements from i + 1 to n - 1 (Sample: 1 to 4)
minIdxintStores index of minimum element found in current pass (Sample: 4)
tempintTemporary variable used to swap arr[i] and arr[minIdx] (Sample: 64)
🎯 1-on-1 Live Mentorship & Free Study Kit

Nail ICSE Selection Sort Logic & Section A Traces Live

Join a 1-on-1 BlueJ tutoring session to eliminate minIdx bugs, practice custom board sorting twists, and score full 15/15 marks in Section B array programs.

💬 WhatsApp Now
🔒 Instant WhatsApp notes + free 60-min 1-on-1 trial session
Confirmed! Our Senior Mentor is sending your study kit & free 1-on-1 demo link on WhatsApp now.

6. Common Mistakes & Top Scorer Tips

  • Avoid Mistake: Swapping `arr[i]` and `arr[j]` inside the inner loop instead of updating `minIdx = j`, which breaks standard Selection Sort behaviour and increases swaps.
  • Avoid Mistake: Comparing `arr[j] < arr[i]` inside the inner loop instead of `arr[j] < arr[minIdx]`, causing `minIdx` to record the last element smaller than `arr[i]` rather than the true minimum.
  • Avoid Mistake: Starting the inner loop at `j = 0` instead of `j = i + 1`, which re-scans already sorted left elements and corrupts earlier passes.
  • Examiner / Mentor Tip: To check a Section A Selection Sort trace in seconds, remember Pass `k` always locks the `k` smallest elements at indices `0` through `k - 1`.
  • Examiner / Mentor Tip: If an ICSE question asks to sort 10 weights in descending order, change `<` to `>` in `if (arr[j] > arr[minIdx])` and rename `minIdx` to `maxIdx` for clarity.
  • Examiner / Mentor Tip: Declare `minIdx` inside the outer loop (or reset `minIdx = i;` at the top of each pass) so stale indices never leak from the previous pass.

7. Interactive Concept Check Quiz

Question: During Selection Sort on {29, 10, 14, 37, 13} in ascending order, what are the array contents right after Pass 2 (i = 1) finishes?

8. Frequently Asked Questions

Why does Selection Sort perform fewer swaps than Bubble Sort?
Bubble Sort swaps elements on the spot every time an adjacent pair is out of order, which can cause up to n*(n-1)/2 swaps in reverse-sorted arrays. Selection Sort only records the index minIdx while scanning and performs a single swap at the end of each pass, capping total swaps at n - 1.
In ICSE Class 10, can I write Selection Sort without the if (minIdx != i) check?
Yes, omitting if (minIdx != i) still produces the exact same sorted output because swapping arr[i] with itself leaves the value unchanged. However, adding that check avoids three unnecessary assignment operations whenever the smallest remaining item is already at index i, which examiners appreciate as clean logic.
Does Selection Sort run faster if the input array is already sorted?
No, standard Selection Sort always scans every remaining element from i + 1 to n - 1 to verify that no smaller value exists, executing all n*(n-1)/2 comparisons even when the array starts completely sorted. Its advantage over Bubble Sort lies in minimizing memory swaps, not reducing total comparisons.

Explore Related Lessons & Free Interactive Tools

Free 1-on-1 Session

Book a Free Demo Class