arrays - 如何在不排序的情况下找到数组中最小的数字?

标签 arrays algorithm sorting c++11

我正在编写一个程序,它在不对数组进行排序的情况下找到数组中的最小数字。输出始终为 0。请解释为什么?

#include<stdio.h>
#include<conio.h>

void main() {
    int num[5] = {5, 2, 1, 6, 9}, i, j;
    int min = num[0];

    for (i=0; i<5; i++) {
        if (min > num[i+1]) {
            min = num[i+1];
        }
    }
    printf("Smallest number is %d", min);

    getch();
}

最佳答案

在这个表达式中:num[i+1] 您试图访问数组外部的元素 - 有效数组索引从零到数组长度减一(即 4 在这种情况下,但 4+1 不在数组中)。

无论如何你不应该硬编码数组长度,而是像这样写你的循环:

for (i = 1; i < num.length; i++) {
    if (num[i] < min) {
        min = num[i];
    }
}

这样它会一直有效,数组的实际长度无关紧要。

关于arrays - 如何在不排序的情况下找到数组中最小的数字?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33069688/

相关文章:

performance - 批量包含查询

php - 每天 24 小时每小时发送 15 次消息

Python:排序函数的参数

python - 对 python 列表的子集进行排序,使其具有与其他列表中相同的相对顺序

arrays - 如何在golang中初始化和设置二维数组

ios - 单击表格行时在 SecondViewController 上显示错误信息

algorithm - 找到小于给定数的 2 个素数的最大乘积

Azure表存储: Order by

python - for循环没有执行两次

javascript - 按值复制数组