Summarise With AI
Back

Selection Sort in Java: A Complete Guide

23 Jan 2026
5 min read

Overview of the Blog

  • Selection Sort in Java works by repeatedly selecting the smallest (or largest) element and placing it in its correct position.
  • It is an in-place, comparison-based sorting algorithm with constant space usage.
  • Selection sort performs O(n²) comparisons in all cases, regardless of input order.
  • The algorithm makes very few swaps, which is useful when write operations are expensive.
  • Best suited for small datasets, learning purposes, and memory-constrained environments.

Introduction

Selection Sort in Java often appears simple at first glance, yet it reveals some of the most important ideas behind how sorting algorithms work.

When you start learning data structures or preparing for interviews, selection sort is usually one of the first algorithms you encounter. Its logic mirrors how people naturally sort items by repeatedly finding the smallest value and placing it where it belongs.

In this complete guide, you will learn how Selection Sort works step by step, how to implement it in Java for arrays and linked lists, how its time and space complexity behaves, and when it should or should not be used in real-world applications.

Selection Sort Algorithm

Selection sort is a basic comparison-based sorting algorithm that arranges data by continually choosing and positioning the lowest (or largest) value from the unsorted region. It is a mainstay in early computer science teaching and a basis for comprehending more complex algorithms due to its simple logic.

Purpose

The main goal of selection sort is to sort elements in ascending or descending order by systematically moving the smallest or largest values to their correct positions.

General Approach

  • The algorithm divides the array into a sorted and an unsorted section.
  • In each iteration, it scans the unsorted portion to find the minimum (or maximum) value.
  • It increases the sorted region by one by replacing this value with the first element of the unsorted part.
  • Until the entire array is sorted, this procedure is repeated.

Key Characteristics

  • In-Place Sorting:
    Selection sort requires just a constant amount of additional space (O(1)) and rearranges entries within the original array.
  • Comparison-Based:
    For an array of size n, it makes around n*(n-1)/2 direct comparisons between items.
  • Predictable Number of Swaps:
    In systems where memory writes are expensive, the algorithm's minimum number of swaps (n – 1) is advantageous.
  • Supports Ascending and Descending Order:
    Selection sort may effortlessly arrange data in any order by modifying the comparison.
  • Not Stable by Default:
    Equal items may lose their original order if the procedure isn't modified for stability.
  • Basis for Other Algorithms:
    The basic idea of consistently selecting the least or maximum is the basis for algorithms like heap sort.
  • Educational Value:
    It is a simple, methodical technique that promotes the growth of fundamental computational and programming skills.

Selection sort is a helpful learning technique because to its simplicity and clarity, even though it is less successful for large or complex datasets.

Optimizations and Variations

  • Stable Selection Sort: Conventional selection sorting lacks stability. To ensure that equal elements maintain their original order, it can be made stable by inserting the minimal element at the appropriate location rather than swapping.
  • Double Selection Sort: In each pass, find both the minimum and maximum elements. Place the minimum at the beginning and the maximum at the end. This reduces the total number of passes by nearly half.
  • Recursive Selection Sort: Instead of using loops, the algorithm can be implemented recursively by selecting the minimum element and recursively sorting the remaining part of the list.

Algorithm of Selection Sort

Selection sort offers clear benefits for small or memory-limited tasks, but also comes with notable drawbacks that limit its use in larger or performance-critical applications.

Advantages

  • Simple to Understand and Implement:
    Beginners may easily learn and write selection sort since its logic is simple.
  • In-Place Sorting (Space Efficient):
    Selection sort only needs a fixed amount of additional memory (O(1) space complexity) and sorts within the original array.
  • Fewest Number of Swaps:
    Selection sort is one of the simplest sorting algorithms; for an array of size n, it does (n – 1) swaps precisely. This is useful in systems like EEPROM or flash storage when memory writes are expensive.
  • Consistent Performance:
    Predictable behavior is provided by the fact that the number of comparisons and swaps is independent of the elements' original order.
  • Ideal for Small Lists and Teaching:
    Ideal for teaching fundamental sorting ideas in educational contexts and for tiny datasets.

Disadvantages

  • Inefficient for Large Arrays:
    Selection sort is significantly slower than algorithms like merge sort or fast sort, especially for big datasets, with a time complexity of O(n²).
  • Not Stable:
    Sorting data with duplicate values may be problematic since selection sort, by default, does not maintain the relative order of equal components.
  • Not Adaptive:
    Regardless of the original arrangement, selection sort always does the same amount of comparisons; it does not benefit from partially sorted data.
  • Selection Sort Shifting Problem:
    In certain implementations, moving the smallest element to the front may require reordering items (especially with linked lists), which might result in increased overhead.
  • More Comparisons Than Necessary:
    Selection sort finishes all possible comparisons even when the array is nearly sorted, in contrast to certain improved or adaptive algorithms.

Summary:

Due to its inefficiency and instability, selection sort is often not utilized for large or performance-critical sorting jobs, although it works well for instructional purposes and tiny or memory-limited applications.

Algorithm of Selection Sort

Selection sort is a basic comparison-based sorting algorithm that arranges data by continually choosing and positioning the lowest (or largest) value from the unsorted region. It is a mainstay in early computer science teaching and a basis for comprehending more complex algorithms due to its simple logic.

Let's have a look at the selection sort algorithm for better understanding with step by step process:

  1. Start with the first element of the array.
  2. For each position i from 0 to n - 2:
    1. Assume the element at position i is the minimum.
    2. For each position j from i + 1 to n - 1:
      • If the element at j is smaller than the current minimum, update the minimum index to j.
    3. After finding the minimum in the unsorted portion, swap it with the element at position i.
  3. Repeat the process until the array is fully sorted.

Selection Sort Pseudocode

SelectionSort(array):
    n = length of array
   
     for i = 0 to n-1:
        min_index = i
       
         for j = i+1 to n:
            if array[j] < array[min_index]:
                min_index = j
       
         if min_index != i:
            swap(array[i], array[min_index])

Explanation:

  1. Outer Loop (i): The outer loop iterates over each element in the array, treating each element as the current position to place the minimum element found.
  2. Inner Loop (j): For each element, the inner loop searches through the rest of the array to find the minimum element.
  3. Find Minimum: If a smaller element is found, it updates the min_index to point to that element.
  4. Swap: The element at the outer loop's current location is swapped with the minimal element once it has been located.

Step-by-Step Working of Selection Sort

By periodically locating the smallest element from the unsorted section and relocating it to its proper location, selection sort arranges an array. Here is a step-by-step explanation of how it works:

1. Initial State

Start with the full array as unsorted.

Example: [64, 25, 12, 22, 11]

2. Iterative Process

From left to right, for every point in the array:

  1. Make the existing index as low as possible.
  2. Find the index of the least value by going through the unsorted section.
  3. Replace the value at the current index with the least value discovered.
  4. The unsorted section decreases while the sorted section increases by one.

3. Manual Walkthrough Example

Let’s sort [64, 25, 12, 22, 11]:

Pass 1

  • Starting from the first element, the algorithm searches for the smallest value in the entire array.
  • It finds 11 as the minimum value.
  • It then swaps 11 with the first element, which is 64.
  • The array becomes: [11, 25, 12, 22, 64]

Pass 2

  • Now the algorithm considers the second part of the array: [25, 12, 22, 64]
  • It finds 12 as the minimum value in this unsorted section.
  • It swaps 12 with 25.
  • The array becomes: [11, 12, 25, 22, 64]

Pass 3

  • The algorithm now focuses on the sub-array: [25, 22, 64]
  • It identifies 22 as the smallest value.
  • It swaps 22 with 25.
  • The array becomes: [11, 12, 22, 25, 64]

Pass 4

  • It now checks the sub-array: [25, 64]
  • 25 is already the smallest, so no swapping is needed.
  • The array remains: [11, 12, 22, 25, 64]

At this point, the entire array is sorted in ascending order.

4. Key Steps in Each Iteration

  • Comparisons: Each pass compares elements in the unsorted section to find the minimum.
  • Swapping: After finding the minimum, a swap places it at the start of the unsorted section.
  • Shifting Problem: Unlike some sorts, selection sort does not shift elements—just swaps.

5. Relative Order of Equal Elements

Selection sort is not stable: equal elements may not maintain their original order after sorting.

This step-by-step approach ensures every element ends up in its correct sorted position, one iteration at a time.

Java program for selection sort

Java's selection sort is a straightforward sorting method that alternates the initial unsorted element with the minimal element from the array's unsorted portion. Until the array is sorted, this procedure is repeated.

Java program for selection sort Code:

public class SelectionSort {

    // Function to perform selection sort
    public static void selectionSort(int[] arr) {
        int n = arr.length;

        // One by one move the boundary of the unsorted subarray
        for (int i = 0; i < n - 1; i++) {
            // Find the minimum element in the unsorted part of the array
            int minIndex = i;
            for (int j = i + 1; j < n; j++) {
                if (arr[j] < arr[minIndex]) {
                    minIndex = j;
                }
            }

            // Swap the found minimum element with the first element
            if (minIndex != i) {
                int temp = arr[i];
                arr[i] = arr[minIndex];
                arr[minIndex] = temp;
            }
        }
    }

    // Function to print the array
    public static void printArray(int[] arr) {
        for (int i = 0; i < arr.length; i++) {
            System.out.print(arr[i] + " ");
        }
        System.out.println();
    }

    public static void main(String[] args) {
        int[] arr = {64, 25, 12, 22, 11};
        
        System.out.println("Original Array:");
        printArray(arr);

        selectionSort(arr);

        System.out.println("Sorted Array:");
        printArray(arr);
    }
}

Output:

Original Array:
64 25 12 22 11 
Sorted Array:
11 12 22 25 64 

Explanation: 

  1. Outer Loop: The outer loop places the smallest element in the array's unsorted section by iterating over each element and using it as the current location.
  2. Inner Loop: The inner loop looks for the lowest element in the array's unsorted section and keeps track of its index (minIndex).
  3. Swap: The first element of the unsorted section (at index i) is substituted for the minimal element after it has been determined.
  4. Repeat: The next smallest element is placed in its proper location with each pass, and this procedure is repeated until the entire array is sorted.
  5. Result: After every pass, the array is sorted in ascending order and printed.

Selection Sort with Linked Lists (Singly Linked List)

Singly linked lists may also be used with Java selection sort, albeit the method is a little different from arrays because of pointer-based structures. Here's a detailed explanation of how it operates:

  • Find the Minimum Node: Traverse the entire unsorted portion of the linked list to find the node with the smallest value. Since linked lists don't allow random access, each search for the minimum requires a full traversal of the remaining nodes.
  • Remove it from the Unsorted List: Once the minimum node is identified, update the pointers to remove this node from its current position in the unsorted list. This typically involves keeping track of the node just before the minimum node.
  • Append It to the End of the Sorted List: Add the removed minimum node to the end of a new sorted list. This sorted list grows one node at a time as the smallest elements are moved from the unsorted list.
  • Repeat Until the List is Empty: Continue looking for the minimum, removing it, and adding it to the sorted list until the unsorted list is empty.
  • Final Result: At the end of the process, the sorted list will include every node in ascending order, while the original unsorted list will be empty.r.

Example: Selection Sort on a Singly Linked List

Let's use selection sort to arrange a singly linked list in ascending order.

Example Input

64 → 25 → 12 → 22 → 11

Java Implementation

class Node {
    int data;
    Node next;
    Node(int data) {
        this.data = data;
        this.next = null;
    }
}
public class SelectionSortLinkedList {

    // Function to perform selection sort on linked list
    public static Node selectionSort(Node head) {
        for (Node current = head; current != null; current = current.next) {
            Node minNode = current;

            // Find the minimum node in the remaining list
            for (Node temp = current.next; temp != null; temp = temp.next) {
                if (temp.data < minNode.data) {
                    minNode = temp;
                }
            }

            // Swap data of current node and minimum node
            int swap = current.data;
            current.data = minNode.data;
            minNode.data = swap;
        }
        return head;
    }

    // Function to print the linked list
    public static void printList(Node head) {
        while (head != null) {
            System.out.print(head.data + " → ");
            head = head.next;
        }
        System.out.println("null");
    }
    public static void main(String[] args) {
        Node head = new Node(64);
        head.next = new Node(25);
        head.next.next = new Node(12);
        head.next.next.next = new Node(22);
        head.next.next.next.next = new Node(11);
        System.out.println("Original List:");
        printList(head);
        head = selectionSort(head);
        System.out.println("Sorted List:");
        printList(head);
    }
}

Output

Original List:
6425122211null
Sorted List:
1112222564null

Step-by-Step Explanation

  1. The algorithm starts from the first node and assumes it holds the minimum value.
  2. It traverses the remaining list to find the node with the smallest value.
  3. Once found, the data values are swapped (not the nodes themselves).
  4. The pointer moves to the next node, and the process repeats.
  5. After each pass, one more node is placed in its correct sorted position.

Bottom Line

The selection process on a single linked list is based only on pointer manipulation, yet it adheres to the same selection concept as arrays. Even though it is ineffective for big lists, it is nevertheless helpful for comprehending pointer-based sorting methods and linked list traversal.

Time and Space Complexity For Selection Sort in Java

Although selection sort is a simple in-place sorting algorithm, its quadratic time complexity limits its effectiveness.

Time Complexity

  • Best Case: O(n²)
    Regardless of the array's original order, selection sort always does the same number of comparisons. Each element is compared with every successive element, even if the array has already been sorted.
  • Average Case: O(n²)
    The algorithm uses nested loops to compare each element with every other unsorted element, resulting in about n*(n-1)/2 comparisons for an array of size n.
  • Worst Case: O(n²)
    The number of comparisons and swaps in the worst-case scenario—a wholly inverted array—remains the same.
  • Swapping:
    Compared to other straightforward sorting algorithms, selection sort only does (n – 1) swaps.

Space Complexity

  • Auxiliary Space: O(1)
    Selection sort is an in-place technique that uses just a constant, small amount of additional memory to sort the array (for variables like indices and temporary storage during swaps). storage during swaps.

Summary Table

Key Points:

  • Selection sort is inefficient for large datasets due to its quadratic time complexity.
  • The algorithm’s in-place nature ensures minimal memory usage (O(1) auxiliary space).
  • The number of comparisons is fixed, but the number of swaps is minimized compared to other basic sorting algorithms.

Comparison with Other Sorting Algorithms

Selection sort is often compared to other basic sorting algorithms like bubble sort and insertion sort. While all three are simple, in-place, comparison-based algorithms with quadratic worst-case time complexity (O(n²)), they differ in their behavior, efficiency, and practical use.

Advantages and Disadvantages of Selection Sort

Selection sort offers clear benefits for small or memory-limited tasks, but also comes with notable drawbacks that limit its use in larger or performance-critical applications.

Advantages

  • Simple to Understand and Implement:
    Beginners may easily learn and write selection sort since its logic is simple.
  • In-Place Sorting (Space Efficient):
    Selection sort only needs a fixed amount of additional memory (O(1) space complexity) and sorts within the original array.
  • Fewest Number of Swaps:
    Selection sort is one of the simplest sorting algorithms; for an array of size n, it does (n – 1) swaps precisely. This is useful in systems like EEPROM or flash storage when memory writes are expensive.
  • Consistent Performance:
    Predictable behavior is provided by the fact that the number of comparisons and swaps is independent of the elements' original order.
  • Ideal for Small Lists and Teaching:
    Ideal for teaching fundamental sorting ideas in educational contexts and for tiny datasets.

Disadvantages

  • Inefficient for Large Arrays:
    Selection sort is significantly slower than algorithms like merge sort or fast sort, especially for big datasets, with a time complexity of O(n²).
  • Not Stable:
    Sorting data with duplicate values may be problematic since selection sort, by default, does not maintain the relative order of equal components.
  • Not Adaptive:
    Regardless of the original arrangement, selection sort always does the same amount of comparisons; it does not benefit from partially sorted data.
  • Selection Sort Shifting Problem:
    In certain implementations, moving the smallest element to the front may require reordering items (especially with linked lists), which might result in increased overhead.
  • More Comparisons Than Necessary:
    Selection sort finishes all possible comparisons even when the array is nearly sorted, in contrast to certain improved or adaptive algorithms.

Summary:

Due to its inefficiency and instability, selection sort is often not utilized for large or performance-critical sorting jobs, although it works well for instructional purposes and tiny or memory-limited applications.

Applications and Use Cases of Selection Sort in Java

Although selection sort isn't the quickest sorting algorithm, there are some situations when its features make it a sensible option. You may take advantage of selection sort's advantages and steer clear of its drawbacks by knowing when and when to utilize it.

1. Educational Applications

Textbooks and programming courses frequently utilize selection sort to demonstrate the principles of sorting algorithms. Its methodical reasoning is simple to see and follow, which makes it perfect for:

  • demonstrating sorting ideas to novices.
  • illustrating the operation of comparison-based sorting.
  • Introducing fundamental data manipulation and algorithmic thinking.

2. Small Datasets

When efficiency is not a major concern, selection sort works well for sorting tiny arrays or collections. For example:

  • sorting a few embedded system configuration parameters.
  • using a classroom tool to arrange a brief list of student IDs or grades.
  • rearranging a few settings menu choices.

It works well when the data amount is small because of its consistent performance and ease of use.

3. Memory-Limited Environments

Selection sort only needs a fixed amount of additional memory (O(1) space complexity) since it is an in-place sorting method. 

  • Because of this, it works well in settings where memory is scarce, such as embedded systems with low RAM.
  • Memory allocation is costly or discouraged in firmware operations.

4. Scenarios Where Minimal Memory Writes Matter

When efficiency is not a major concern, selection sort works well for sorting tiny arrays or collections. For example:

  • sorting a few embedded system configuration parameters. using a classroom tool to arrange a brief list of student IDs or grades. rearranging a few settings menu choices.
  • It works well when the data amount is small because of its consistent performance and ease of use.

5. Sorting Different Data Types

Selection sort only needs a fixed amount of additional memory (O(1) space complexity) since it is an in-place sorting method. Because of this, it works well in settings where memory is scarce, such as embedded systems with low RAM.

  • Memory allocation is costly or discouraged in firmware operations.

6. When Not to Use Selection Sort

Although selection sort has various applications, it is often not advised for:

  • large datasets because of their O(n²) time complexity.
  • Faster sorting algorithms, such as Quick Sort or Merge Sort, are preferred in performance-critical applications.

You may decide whether Java selection sort is the best option for your assignment by comprehending these applications and usage cases. Even while it isn't appropriate in every situation, its predictability and clarity guarantee that it will always be a useful tool for programmers.

Conclusion

The Selection Sort algorithm in Java is simple yet useful for understanding sorting concepts. Its consistent behavior, minimum swaps, and constant space use make it useful for tiny inputs and instructional purposes, but its O(n²) time complexity makes it inappropriate for big datasets. Developers get a solid foundation in algorithmic thinking by studying selection sort, which aids in their comprehension and assessment of more complex sorting methods.

Key Takeaways

  1. Regardless of whether the input is sorted or not, selection sort always does the same amount of comparisons.
  2. Because the method sorts items in situ, space complexity stays O(1).
  3. Because there are minimal swaps (n − 1), it is suitable in scenarios where write operations are costly.
  4. Although selection sort is not stable by default, order may be maintained by modifying it.
  5. Selection sort finishes all possible comparisons even when the array is nearly sorted, in contrast to certain improved or adaptive algorithms.

Frequently Asked Questions

1. What is Selection Sort in Java?

A Java comparison-based sorting technique called Selection Sort chooses the least (or largest) element from the array's unsorted portion and positions it appropriately. This procedure is carried out again until the array is completely sorted.

2. Why is Selection Sort not suitable for large datasets?

Selection Sort becomes expensive for big datasets because it always conducts O(n²) comparisons, regardless of the input order. In these situations, faster algorithms like Quick Sort or Merge Sort are more appropriate.

3. Is Selection Sort stable?

Because Selection Sort is not stable by default, the relative order of equal components could not be preserved. However, a stable version may be produced by inserting instead of swapping.

4. Can Selection Sort be used for objects in Java?

Yes. You can sort objects using Selection Sort by implementing the Comparable interface or using a Comparator. This allows you to define custom sorting logic for objects.

5. What is the space complexity of Selection Sort?

The space complexity of Selection Sort is O(1). With the exception of a few variables for indexing and swapping, this in-place sorting method doesn't need additional memory.

6. How does Selection Sort differ from Bubble Sort?

Selection Sort does fewer swaps than Bubble Sort, despite the fact that both are straightforward O(n²) sorting algorithms. For systems where write operations are costly, this improves Selection Sort.

7. When should I use Selection Sort in real-world applications?

Selection Sort is ideal for small datasets, educational purposes, and embedded systems with limited write cycles (e.g., EEPROM). It is not recommended for performance-critical tasks.

Summarise With Ai
ChatGPT
Perplexity
Claude
Gemini
Gork
ChatGPT
Perplexity
Claude
Gemini
Gork
Chat with us
Chat with us
Talk to career expert