Home  >  Article  >  Backend Development  >  Explain the process of selection sorting in C language

Explain the process of selection sorting in C language

王林
王林forward
2023-09-01 13:57:07907browse

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.

The process of selection sorting

  • 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 -

Explain the process of selection sorting in C language

First pass

Sm = a[0] = 30 Sm

a[1]

a[2]

a[3]

a[4]

10 50 40 30 20

Second pass

Explain the process of selection sorting in C language

Sm = a[1] = 50 sm

a[2]

a[3]

a[4]

10 20 40 30 50

Third pass

Explain the process of selection sorting in C language

Sm = a[2] = 40 Sm

a[3]

a[4] The Chinese translation is:

a[3]

a[4]

10 20 30 40 50

Fourth time

Explain the process of selection sorting in C language

Sm = a[3] = 40 Sm

a[4]

Procedure

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;
   }
}

Example

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;
}

Output

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!

Statement:
This article is reproduced at:tutorialspoint.com. If there is any infringement, please contact admin@php.cn delete