选择排序是一种攻击性算法,用于从数组中找到最小的数字,然后将其放置到第一个位置。下一个要遍历的数组将从索引开始,靠近放置最小数字的位置。
选择排序的过程
选择元素列表中第一个最小的元素并将其放置在第一个位置。
对列表中的其余元素重复相同的操作,直到所有元素都获得已排序。
考虑以下列表 -

立即学习“C语言免费学习笔记(深入)”;
第一次通过
Sm = a[0] = 30 Sm
a[1]
a[2]
a[3]
a[4]
10 50 40 30 20
第二遍

Sm = a[1] = 50 sm
a[2]
a[3]
a[4]
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
的中文翻译为:a[3] < sm $\square$ $\square$ 30 <40 (T) $\square$ $\square$ 40
a[4] < sm $\square$ $\square$ 50<40 (F) $\square$ $\square$ 30 用sm值交换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
Procedure
请参考下面的步骤进行选择排序。
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;
}
}示例
以下是选择排序技术的C程序−
#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;
}输出
当执行上述程序时,会产生以下结果 -
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











