Home >Backend Development >C++ >C program for selection sorting
Selection sort is an aggressive algorithm that works by finding the smallest number from an array and placing it at the first position. The next array to be traversed will start at the next index where the smallest number is.
Let us take an example to illustrate this concept more clearly.
We have an array {6, 3, 8, 12, 9} and the smallest element in this array is 3. So we put 3 in the first position and after that the array will look like {3, 6, 8, 12, 9} . Now we will find the smallest number again, but this time we will not consider 3 in the search since it is in its place. Find the next smallest element, 6, create an array containing 6 at the second position, and search in the array again until the array is sorted.
How the selection sort algorithm works -
The selection sort algorithm follows the following steps
Let us take an array {20, 12, 23, 55,21}
Set the first element of the array to the minimum value.
Min value = 20
Compare the minimum value with the next element and if it is less than the minimum value assign that element as the minimum value. Do this until the end of the array.
is compared with 12: 20 > 12, the minimum value = 12
is compared with 23: 12 is compared with 55: 12
Compare with 21: 12
Place the minimum value at the first position (index 0) of the array.
Array = {12, 20,23, 55, 21}
For the next iteration, start sorting from the first unsorted element.
Array = {12, 20,23, 55, 21}
Start searching from 20 and place the element with the minimum value next.
Iteration 2:
Min = 20
compared to 23: 20
compared to 55: 20
Compared with 21: 20
Minimum value remains unchanged,
Array = {12, 20, 23, 55, 21}
Iteration 3:
Minimum value = 23.
Compare with 55: 23
Compare with 21: 23 > 21, minimum value = 21
Minimum value moved to index= 2
Array = {12, 20, 21, 55, 23}
Iteration 4:
Min value = 55
Compare to 23: 23
Minimum value moved to index 3 Array = { 12 , 20 , 21 , 23 , 55 }
#include <stdio.h> int main() { int arr[10]={6,12,0,18,11,99,55,45,34,2}; int n=10; int i, j, position, swap; for (i = 0; i < (n - 1); i++) { position = i; for (j = i + 1; j < n; j++) { if (arr[position] > arr[j]) position = j; } if (position != i) { swap = arr[i]; arr[i] = arr[position]; arr[position] = swap; } } for (i = 0; i < n; i++) printf("%d\t", arr[i]); return 0; }
0 2 6 11 12 18 34 45 55 99
The above is the detailed content of C program for selection sorting. For more information, please follow other related articles on the PHP Chinese website!