是否按照选择排序算法编写了以下C代码?我对此有些困惑。但是,它给出了正确的结果。
#include <stdio.h>
int main() {
int n;
printf("Enter size of array: ");
scanf("%d", &n);
int a[n], i = 0, j, min;
while (i < n) {
printf("Enter no. %d:", i + 1);
scanf("%d", &a[i]);
i++;
}
for (i = 0; i < n; i++) {
for (j = i, min = a[i]; j < n; j++) {
if (a[j] < min)
min = a[j];
else
continue;
a[j] = a[i];
a[i] = min;
}
}
for (i = 0; i < n; i++)
printf("%d ", a[i]);
return 0;
}
答案 0 :(得分:-2)
选择排序
#include<stdio.h>
int main() {
int array[100], n, c, d, position, swap;
printf("Enter number of elements\n");
scanf("%d", &n);
printf("Enter %d integers\n", n);
for (c = 0; c < n; c++)
scanf("%d", &array[c]);
for (c = 0; c < (n - 1); c++)
{
position = c;
for (d = c + 1; d < n; d++)
{
if (array[position] > array[d])
position = d;
}
if (position != c)
{
swap = array[c];
array[c] = array[position];
array[position] = swap;
}
}
printf("Sorted list in ascending order:\n");
for (c = 0; c < n; c++)
printf("%d\n", array[c]);
return 0;
}