C编程:创建10个元素的数组,冒泡排序算法,Return数组的最小值和最大值

C Programming: reate 10 Element Array, Bubblesort Algorithm, Return Min and Max Values of Array

所以实际问题只是要求接受一个 10 元素数组和 return 最小值和最大值。我很习惯在 Matlab/GNUoctave 中处理数组,但今天是我第一次在 C 中处理它们。

无论如何,我想我想知道的是是否有比像我那样使用 for 循环输入数组更好的方法。

此外,我无法弄清楚如何让我的 bubblesort if 块继续循环直到数组排序。我尝试 "while(;;)" 但没有成功,并开始研究布尔变量但没有找到我要找的东西。

另外,如果有更好的方法一起做这件事,我在这里学习。就像 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)

首先,冒泡排序通常需要多次通过才能对整个 collection 进行排序。每次将 "bubbles" 一个项目传递到正确的位置。

第二个问题是,当您比较项目 nn + 1 时,n 在 ten-element 数组中最好不要超过八个。

考虑到这两点,最简单(不一定是最有效)的冒泡排序是:

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
        }
    }
}

当然,只有当您需要对数组进行排序时,这一切才有意义。您的问题标题似乎表明了这一点,但 body 没有。

所以,如果唯一的要求是return最小值和最大值,则不需要排序。你可以做类似的事情:

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) 实际上还有一个 第三个 问题,如果您输入的内容 不是 int。如果发生这种情况,则不会设置该值,并且输入流将保持在 尝试读取之前 的状态。使用 scanf 通常 总是 检查 return 代码,例如:

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;
    }
}

我将其分开,因为虽然拥有健壮的代码更好,但通常认为这对于教育代码来说不是必需的。然而,你最好早点养成这个习惯。

冒泡排序具有 O(n^2) 时间复杂度,对于此任务不是必需的。您对冒泡排序的实现也是错误的。您将需要一个运行 10 次(或在没有元素被交换时终止)的外部 for loop。 我将为您的问题概述一个更简单的方法

smallest = INF  //very large value
largest = -INF  //very small value
for (i=0; i < 10; i++) {
    smallest  = min(smallest, a[i])
    largest = max(largest, a[i])
}