Sort the following number using selection sort and give the required steps. 31 27 42 34 76 61 10 4
Q.) Sort the following number using selection sort and give the required steps. 31 27 42 34 76 61 10 4
Subject: data structureSelection Sort
Steps:
- Find the minimum element in the unsorted portion of the list.
- Swap the minimum element with the leftmost unsorted element.
- Repeat steps 1 and 2 until the entire list is sorted.
Example:
Given the list [31, 27, 42, 34, 76, 61, 10, 4]
, the following steps are taken:
- Find the minimum element in the unsorted portion of the list, which is
4
. Swap the minimum element with the leftmost unsorted element, which is
31
:[4, 27, 42, 34, 76, 61, 10, 31]
Repeat steps 1 and 2 until the entire list is sorted:
- Find the minimum element in the unsorted portion of the list, which is
10
. - Swap the minimum element with the leftmost unsorted element, which is
27
:[4, 10, 42, 34, 76, 61, 27, 31]
- Find the minimum element in the unsorted portion of the list, which is
- Find the minimum element in the unsorted portion of the list, which is
27
. Swap the minimum element with the leftmost unsorted element, which is
42
:[4, 10, 27, 34, 76, 61, 42, 31]
Find the minimum element in the unsorted portion of the list, which is
31
.Swap the minimum element with the leftmost unsorted element, which is
34
:[4, 10, 27, 31, 76, 61, 42, 34]
Find the minimum element in the unsorted portion of the list, which is
34
.Swap the minimum element with the leftmost unsorted element, which is
61
:[4, 10, 27, 31, 34, 61, 42, 76]
Find the minimum element in the unsorted portion of the list, which is
42
.Swap the minimum element with the leftmost unsorted element, which is
76
:[4, 10, 27, 31, 34, 61, 76, 42]
- The list is now sorted:
[4, 10, 27, 31, 34, 42, 61, 76]
.
Time Complexity:
The time complexity of selection sort is O(n^2)
, where n
is the length of the list. This is because the algorithm iterates through the list twice: once to find the minimum element, and once to swap it with the leftmost unsorted element.
Space Complexity:
The space complexity of selection sort is O(1)
, as it does not require any additional memory space.