The basic idea of the selection sorting algorithm is to select the smallest number in the array and put it in front of the array. In C language, we can use two for loops, starting from the second element of the array and traversing backward. , find the smallest number and put it in the first position, then find the smallest number from the remaining array and put it in the second position, and so on until the array is sorted.
The implementation principle of the selection sorting method:
First determine the next number of the smallest number Whether the index is 0, if not, it means that the smallest number is not the first element, then this number and the first element are swapped, so that the smallest number in one round is found and placed on the far left.
【Video tutorial recommendation: C language tutorial】
Code example:
Use the selection sort method to sort a set of manually entered data from small to large. The data are 52, 36, 2, 39, 56, 45, 78. ,92,15,52.
Implementation code:
#include <stdio.h> int main() { int i,j,t,a[11]; //定义变量及数组为基本整型 printf("请输入10个数:\n"); for(i=1;i<11;i++) scanf("%d",&a[i]); //从键盘中输入要排序的10个数字 for(i=1;i<=9;i++) for (j=i+1;j<=10;j++) if(a[i]>a[j]) //如果前一个数比后一个数大,则利用中间变量t实现两值互换 { t=a[i]; a[i]=a[j]; a[j]=t; } printf("排序后的顺序是:\n"); for(i=1;i<=10;i++) printf("%5d", a[i]); //输出排序后的数组 printf("\n"); return 0; }
Output:
Code description:
Two for loop statements are used in the code. The first for loop determines the position, which stores the smallest number selected after each selection and exchange from the sequence to be sorted. The second for loop is to compare the number at a certain position with the number in the subsequent interval to be sorted.
The above is the detailed content of How to implement selection sort algorithm in C language (code example). For more information, please follow other related articles on the PHP Chinese website!