Computer Science

Selection Sort – Sorting Algorithm

Selection Sort

Selection Sort is a simple but inefficient sorting algorithm. It works by repeatedly finding the smallest (or largest) element in the unsorted portion of the array and swapping it with the first element of the unsorted portion.


1. How It Works

  1. Treat the first element as the starting point of the unsorted portion.
  2. Find the smallest element in the unsorted portion.
  3. Swap it with the first element of the unsorted portion.
  4. Move the starting point of the unsorted portion to the next element.
  5. Repeat until all elements are sorted.

2. Characteristics

  • Time Complexity:
    • Best/Average/Worst case: O(n^2)
  • Space Complexity:
    • Requires almost no additional memory: O(1)
  • Unstable Sort:
    • Does not preserve the relative order of equal elements.

3. Example Process

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

  1. First Pass:
    • Find the smallest element: 11.
    • Swap 11 with 64 → [11, 25, 12, 22, 64].
  2. Second Pass:
    • Find the smallest element: 12.
    • Swap 12 with 25 → [11, 12, 25, 22, 64].
  3. Third Pass:
    • Find the smallest element: 22.
    • Swap 22 with 25 → [11, 12, 22, 25, 64].
  4. Fourth Pass:
    • Find the smallest element: 25.
    • Swap 25 with itself → [11, 12, 22, 25, 64].
  5. Final Pass:
    • Array is fully sorted.

4. Advantages and Disadvantages

Advantages:

  • Simple and easy to understand.
  • Requires no additional memory for sorting.

Disadvantages:

  • Time complexity is O(n^2), making it inefficient for large datasets.
  • It is not a stable sort, meaning the relative order of equal elements is not guaranteed.

5. Java Implementation

import java.util.Arrays;

public class SelectionSort {
    public static void selectionSort(int[] arr) {
        int n = arr.length;

        // Loop through all array elements
        for (int i = 0; i < n - 1; i++) {
            // Find the minimum element in the unsorted part
            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
            int temp = arr[minIndex];
            arr[minIndex] = arr[i];
            arr[i] = temp;
        }
    }

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

        selectionSort(arr);

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

6. Python Implementation

def selection_sort(arr):
    n = len(arr)
    for i in range(n):
        # Find the index of the smallest element in the unsorted part
        min_index = i
        for j in range(i + 1, n):
            if arr[j] < arr[min_index]:
                min_index = j
        
        # Swap the smallest element with the first element of the unsorted part
        arr[i], arr[min_index] = arr[min_index], arr[i]

# Example usage
if __name__ == "__main__":
    arr = [64, 25, 12, 22, 11]
    print("Original Array:", arr)

    selection_sort(arr)

    print("Sorted Array:", arr)

7. Optimizations

  • Avoid Unnecessary Swaps: Skip the swap if the minimum element is already in its correct position.
  • Loop Termination: Terminate early if no swaps are needed in a pass (though rare in selection sort).

8. Applications

Selection Sort is useful in scenarios where:

  • The dataset is small.
  • Additional memory usage needs to be minimized.

Although Selection Sort is simple and educational, it is rarely used in practical applications due to its inefficiency. For better performance, algorithms like Merge Sort or Quick Sort are preferred.

Aquinas

Hello! I'm Aquinas, a lifelong learner who finds everything in the world fascinating. I can’t ignore my curiosity, and this blog is where I document my journey of learning, exploring, and understanding various topics. I don’t limit myself to a single field—I enjoy diving into science, philosophy, technology, the arts, and more. For me, learning isn’t just about gathering information; it’s about applying knowledge, analyzing it from different perspectives, and discovering new insights along the way. Through this blog, I hope to record my learning experiences, share ideas, and connect with others who have a similar passion for knowledge. Let’s embark on this journey of exploration together! 😊

Recent Posts

What Is EPS(Earnings Per Share)?

When analyzing a stock, one of the first financial indicators you’ll encounter is EPS, or Earnings Per Share. It’s one… Read More

8 months ago

What is Market Capitalization? Everything Investors Need to Know

When you look at a stock’s profile on a financial website, one of the first things you’ll see is its… Read More

8 months ago

The MIT License

In the world of open-source software, simplicity and flexibility are often just as important as legal protection. That’s why the… Read More

9 months ago

Mozilla Public License (MPL)

If you want your software to be open source, but still compatible with commercial use—and not as restrictive as the… Read More

9 months ago

The Apache License 2.0

When it comes to open-source software, developers and businesses alike need licenses that balance freedom, legal clarity, and long-term security.… Read More

9 months ago

BSD (Berkeley Software Distribution) License

If you’re working on open-source projects or choosing third-party libraries for your software, understanding software licenses is essential. Among the… Read More

9 months ago