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
- Comparison among Bubble Sort, Selection Sort and Insertion Sort
- Program to sort an array of strings using Selection Sort
- Stable Selection Sort
- Recursive Selection Sort
- 8086 program for selection sort
- Sorting Algorithms Visualization | Selection Sort
- Iterative selection sort for linked list
- C++ program for Sorting Dates using Selection Sort
- A sorting algorithm that slightly improves on selection sort
- C program for Time Complexity plot of Bubble, Insertion and Selection Sort using Gnuplot
- Recursive selection sort for singly linked list | Swapping node links
- Job Selection Problem - Loss Minimization Strategy | Set 2
- Why Quick Sort preferred for Arrays and Merge Sort for Linked Lists?
- Insertion sort to sort even and odd positioned elements in different orders
- Bucket Sort To Sort an Array with Negative Numbers