The selection sort algorithm sorts an array by repeatedly finding the minimum element (considering ascending order) from unsorted part and putting it at the beginning. The algorithm maintains two subarrays in a given array.
1) The subarray which is already sorted.
2) Remaining subarray which is unsorted.
In every iteration of selection sort, the minimum element (considering ascending order) from the unsorted subarray is picked and moved to the sorted subarray.
Following example explains the above steps:
arr = 64 25 12 22 11 // Find the minimum element in arr[0...4] // and place it at beginning 11 25 12 22 64 // Find the minimum element in arr[1...4] // and place it at beginning of arr[1...4] 11 12 25 22 64 // Find the minimum element in arr[2...4] // and place it at beginning of arr[2...4] 11 12 22 25 64 // Find the minimum element in arr[3...4] // and place it at beginning of arr[3...4] 11 12 22 25 64
Flowchart of the Selection Sort:
Sorted array: 11 12 22 25 64
Time Complexity: O(n2) as there are two nested loops.
Auxiliary Space: O(1)
The good thing about selection sort is it never makes more than O(n) swaps and can be useful when memory write is a costly operation.
In Place : Yes, it does not require extra space.
Other Sorting Algorithms on GeeksforGeeks/GeeksQuiz:
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.
- Comparison among Bubble Sort, Selection Sort and Insertion Sort
- Program to sort an array of strings using Selection Sort
- C++ program for Sorting Dates using Selection Sort
- Recursive Selection Sort
- Recursive selection sort for singly linked list | Swapping node links
- A sorting algorithm that slightly improves on selection sort
- Stable Selection Sort
- 8086 program for selection sort
- Iterative selection sort for linked list
- Sorting Algorithms Visualization | Selection Sort
- C program for Time Complexity plot of Bubble, Insertion and Selection Sort using Gnuplot
- Job Selection Problem - Loss Minimization Strategy | Set 2
- Why Quick Sort preferred for Arrays and Merge Sort for Linked Lists?
- Odd-Even Sort / Brick Sort
- Bucket Sort To Sort an Array with Negative Numbers
- Serial Sort v/s Parallel Sort in Java
- C/C++ Program for Odd-Even Sort / Brick Sort
- Java Program for Odd-Even Sort / Brick Sort
- Insertion sort to sort even and odd positioned elements in different orders
- Quick Sort vs Merge Sort