Selection Sort Algorithm
This type of sorting is called Selection Sort as it works by repeatedly sorting elements. That is: we first find the smallest value in the array and exchange it with the element in the first position, then find the second smallest element and exchange it with the element in the second position, and we continue the process in this way until the entire array is sorted.
- Start with the first element of the array.
- Assume the first element is the smallest in the unsorted portion.
- Traverse through the unsorted portion of the array (all elements after the current position).
- Compare each element with the current smallest element:
- If a smaller element is found, update the smallest element's index.
- Once the smallest element in the unsorted part is identified, swap it with the first unsorted element (the current position).
- This moves the smallest element into its correct position in the sorted part.
- Increment the boundary of the sorted part by one (move to the next position).
- Repeat steps 1 to 3 for the remaining unsorted part of the array.
- Continue until the entire array is sorted.
Example
Consider the following depicted array as an example.
For the first position in the sorted list, the whole list is scanned sequentially. The first position where 14 is stored presently, we search the whole list and find that 10 is the lowest value.
So we replace 14 with 10. After one iteration 10, which happens to be the minimum value in the list, appears in the first position of the sorted list.
For the second position, where 33 is residing, we start scanning the rest of the list in a linear manner.
We find that 14 is the second lowest value in the list and it should appear at the second place. We swap these values.
After two iterations, two least values are positioned at the beginning in a sorted manner.
The same process is applied to the rest of the items in the array −
0 comments:
Post a Comment