Selection sort is an aggressive algorithm used to find the smallest number from an array and place it in the first position. The next array to be traversed will start at the index, close to where the smallest number is placed.
Select the first smallest element in the list of elements and place it in the first position.
Repeat the same operation for the remaining elements in the list until all elements are sorted.
Consider the following list -
Sm = a[0] = 30 Sm
a[1] < sm $\ square$ $\square$ 50 <30 (F) $\square$ $\square$ 30< sm $\square$ $\square$ 50 <30 (F) $\square$ $\square$ 30
a[2] < sm $\square$ $ \square$ 40 <30 (F) $\square $ $\square$ 20$\square$ Exchange a[0] with sm value< sm $\square$ $ \square$ 40 <30 (F) $\square$ $\square$ 20$\square$ 将 a[0] 与 sm 值交换
a[3] < sm $\square$ $\square $ 10 <30 (T) $\square$ $ \square$ 10< sm $\square$ $\square $ 10 <30 (T) $\square$ $\square$ 10
a[4] < sm $\square$ $\square$ 20<10 (F) $\square$ $\square 10 $< sm $\square$ $\square$ 20<10 (F) $\square$ $\square 10 美元
10 50 40 30 20
Sm = a[1] = 50 sm
a[2] < sm $\square$ $\square$ 40 <50 (T) $\square$ 40 $\square$< sm $\square$ $\square$ 40 <50 (T) $\square$ 40 $\square$
a[3] < sm $\square$ $ \square$ 30 <40 (T) $\square$ 30 Exchange a[1] with sm value< sm $\square$ $ \square$ 30 <40 (T) $\square$ 30 将 a[1] 与 sm 值交换
a[4] < sm $\square$ $\square$ 20<30 (T) $ \square$ 20< sm $\square$ $\square$ 20<30 (T) $ \平方$ 20
10 20 40 30 50
Sm = a[2] = 40 Sm
a[3] < sm $\ square$ $\square$ 30 <40 (T) $\square$ $\square$ 40
a[4] < sm $\square$ $\square$ 50<40 (F) $ \square$ $\square$ 30 exchange a[2] with sm value
The Chinese translation is:a[3] < sm $\square$ $\square$ 30 <40 (T) $ \square$ $\square$ 40
a[4] < sm $\square$ $\square$ 50<40 (F) $\square$ $\square$ 30 Use sm value to exchange a[ 2]
10 20 30 40 50
Sm = a[3] = 40 Sm
a[4] < $\square$ $\square$ sm 50 <40 (F) $\square$ 40 $\square$ exchange a[3] with sm value
Please refer to the following steps to select and sort.
for (i=0; i<n-1; i++){ sm=i; for (j=i+1; j<n; j++){ if (a[j] < a[sm]) sm=j; } t=a[i]; a[i] = a[sm]; a[sm] = t; } }
The following is a C program for the selection sort technique −
#include<stdio.h> int main(){ int a[50], i,j,n,t,sm; printf("enter the No: of elements in the list:</p><p>"); scanf("%d", &n); printf("enter the elements:</p><p>"); for(i=0; i<n; i++){ scanf ("%d", &a[i]); } for (i=0; i<n-1; i++){ sm=i; for (j=i+1; j<n; j++){ if (a[j] < a[sm]){ sm=j; } } t=a[i]; a[i]=a[sm]; a[sm]=t; } printf ("after selection sorting the elements are:</p><p>"); for (i=0; i<n; i++) printf("%d\t", a[i]); return 0; }
When the above program is executed, the following results are produced -
enter the No: of elements in the list: 4 enter the elements: 45 12 37 68 after selection sorting the elements are: 12 37 45 68
The above is the detailed content of Explain the process of selection sorting in C language. For more information, please follow other related articles on the PHP Chinese website!