18
OctSelection 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!
Take our Datastructures skill challenge to evaluate yourself!

In less than 5 minutes, with our skill challenge, you can identify your knowledge gaps and strengths in a given skill.