所以实际问题只是要求接受一个 10 元素数组并返回最小值和最大值。我非常习惯在 Matlab/GNUoctave 中处理数组,但今天是我第一次在 C 中处理它们。
无论如何,我想我想知道的是,是否有比像我那样使用 for 循环输入数组更好的方法。
此外,我无法弄清楚如何让我的冒泡排序 if block 继续循环直到数组排序。我尝试了“while(;;)”但没有成功,并开始研究 bool 变量但没有找到我要找的东西。
此外,如果有更好的方法可以完全做到这一点,我会在这里学习。就像 bubblesort 对此很愚蠢,我不知道。我怀疑是的。更长的阵列可能需要很长时间?
#include <stdio.h>
int main()
{
int a[10];
int i;
int k;
int temp;
for (i=0; i < 10; i++)
{
printf("Enter an integer: ");
scanf("%d",&a[i]);
}
for (i=0; i < 10; i++)
{
if (a[i] > a[i+1])
{
temp = a[i];
a[i] = a[i+1];
a[i+1] = temp;
}
}
printf("Smallest = %i\nLargest = %i\n",a[0],a[9]);
return 0;
}
最佳答案
我发现您的代码存在两个直接问题(a)。
首先,冒泡排序通常需要多次通过才能对整个集合进行排序。每次传递都会将单个项目“冒泡”到其正确位置。
第二个问题是,当您比较项目 n
和 n + 1
时,n
最好不要超过 8一个十元素数组。
考虑到这两点,最简单(不一定是最有效)的冒泡排序是:
for (int pass = 1; pass <= 10; ++pass) {
for (int idx = 0; idx < 9; ++idx) {
if (a[idx] > a[idx + 1]) {
int temp = a[idx];
a[idx] = a[idx + 1];
a[idx + 1] = temp;
}
}
}
在完成排序的传递之后退出的一个(而不是无论如何都要进行十次传递)将使用一个标志来指示这一点:
int madeSwap = 1; // or bool madeSwap (after #include <stdbool.h>).
while (madeSwap) {
madeSwap = 0; // false for stdbool
for (int idx = 0; idx < 9; ++idx) {
if (a[idx] > a[idx + 1]) {
int temp = a[idx];
a[idx] = a[idx + 1];
a[idx + 1] = temp;
madeSwap = 1; // true for stdbool
}
}
}
当然,只有当您需要对数组进行排序时,这一切才有意义。您的问题标题似乎表明了这一点,但正文却没有。
所以,如果唯一的要求是返回最小值和最大值,则不需要排序。你可以做类似的事情:
int minVal = a[0], maxVal = a[0];
for (int idx = 1; idx < 10; ++idx) {
if (a[idx] < minVal) minVal = a[idx];
if (a[idx] > maxVal) maxVal = a[idx];
}
// minVal and maxVal now hold the minimum and maximum value respectively.
(a) 实际上还有一个第三个问题,如果您输入的内容不是 整数
。如果发生这种情况,该值将不会被设置,输入流将保持在尝试读取之前的状态。使用 scanf
通常应该总是检查返回代码,例如:
for (int i = 0; i < 10; i++) {
printf("Enter an integer: ");
if (scanf("%d", &a[i]) != 1) {
puts("Invalid data in input stream, will exit.");
return 1;
}
}
我将其分开,因为虽然拥有健壮的代码更好,但通常认为这对于教育代码来说不是必需的。但是,最好早点养成这个习惯。
关于C编程 : reate 10 Element Array, 冒泡排序算法,返回数组的最小值和最大值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50403738/