Bootcamps
Masterclasses
Menu
Courses
Account
Login / Sign Up
Selection Sort Algorithm

Selection Sort Algorithm

Beginner 3 min read 23 Sep 2025 1.64K views
Selection Sort Algorithm

Selection Sort Algorithm (Optimized)

The Selection Sort Algorithm is a simple comparison-based sorting algorithm that divides the input array into a sorted and an unsorted region. In each iteration, it finds the minimum element in the unsorted region and places it at the beginning of the sorted region. The optimization involves minimizing swaps by identifying the minimum element's index in each pass and performing only one swap per iteration, rather than swapping every time a smaller element is found.

DSA skills can boost your tech salary by 25% in 2025. Enroll in our Free DSA Course with Certificate today!

Example:

  • Input: nums = [64, 25, 12, 22, 11]
  • Output: [11, 12, 22, 25, 64]
  • Explanation: The array is sorted in ascending order.

Logic

Enter an array of numbers (comma-separated) to sort it using the optimized Selection Sort algorithm.

Program (Python - Optimized Selection Sort)

The following Python code implements an optimized Selection Sort algorithm with O(n²) time complexity in the worst and average cases, where n is the length of the array. The optimization reduces the number of swaps.


def selectionSort(nums):
    n = len(nums)
    for i in range(n):
        # Find the minimum element in the unsorted portion
        min_idx = i
        for j in range(i + 1, n):
            if nums[j] < nums[min_idx]:
                min_idx = j
        # Swap only once per iteration
        if min_idx != i:
            nums[i], nums[min_idx] = nums[min_idx], nums[i]
    return nums

# Example usage
nums = [64, 25, 12, 22, 11]
print(selectionSort(nums))  # Output: [11, 12, 22, 25, 64]

Output

For the input nums = [64, 25, 12, 22, 11], the output is:


[11, 12, 22, 25, 64]

Explanation:

The array is sorted in ascending order using the optimized selection sort algorithm.

India’s tech hubs have 12,000+ openings for certified Java full stack developers. Start now with our Java full stack training and seize prime opportunities!

Test yourself in 5 minutes

Take the free Datastructures skill challenge to see your strengths and the gaps to fix next.

Start the challenge
Share LinkedIn X Facebook WhatsApp

About the author

Amit Kumar

Amit Kumar

Software Engineer And Author

Experienced Software Engineer with a demonstrated history of working in the professional training & coaching industry. Skilled in Asp.net MVC, Angular, Language Integrated Query (LINQ), SQL, C++, and HTML. Strong engineering professional graduated from Sathyabama University.

Keep learning

Courses that go with this tutorial