1. 作用
将一维随机乱序数组按从小到大顺序排列
2. 原理图
3. 代码
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main(void)
{
int a[5] = {0};
int len = sizeof(a) / sizeof(a[0]);
int i = 0;
int j = 0;
int minpos = 0;
int tmp = 0;
srand(time(NULL));
for (i = 0; i < len; i++)
{
a[i] = rand() % 100;
}
printf("排序前:");
for (i = 0; i < len; i++)
{
printf("%-2d ", a[i]);
}
putchar('\n');
for (j = 0; j < len-1; j++)
{
minpos = j;
for (i = j+1; i < len; i++)
{
if (a[i] < a[minpos])
{
minpos = i;
}
}
if (minpos != j)
{
tmp = a[j];
a[j] = a[minpos];
a[minpos] = tmp;
}
}
printf("排序后:");
for (i = 0; i < len; i++)
{
printf("%-2d ", a[i]);
}
putchar('\n');
return 0;
}