gpt4 book ai didi

c - 这个嵌套循环的简单解释是什么

转载 作者:行者123 更新时间:2023-11-30 15:39:45 25 4
gpt4 key购买 nike

#include <stdio.h>
#include <stdlib.h>
#include <time.h>
main(){
int ctr, inner, outer, didSwap, temp;
int nums[10];
time_t t;

srand(time(&t));

for (ctr = 0; ctr < 10; ctr++){
nums[ctr] = (rand() % 99) + 1;
}

// Now list the array as it currently is before sorting
puts("\nHere is the list before the sort:");
for (ctr = 0; ctr < 10; ctr++) {
printf("%d\n", nums[ctr]);
}

// Sort the array
for (outer = 0; outer < 9; outer++) {
didSwap = 0; //Becomes 1 (true) if list is not yet ordered
for (inner = outer; inner < 10; inner++) { // << I dont uunderstand this nested loop ?
if (nums[inner] < nums[outer]) {
temp = nums[inner];
nums[inner] = nums[outer];
nums[outer] = temp;
didSwap = 1;
}
}

if (didSwap == 0) {
break;
}
}

// Now list the array as it currently is after sorting
puts("\nHere is the list after the sort:");
for (ctr = 0; ctr < 10; ctr++) {
printf("%d\n", nums[ctr]);
}

return(0);
}

有时我真的很难处理代码,这段代码来自一本为像我这样的新手教授 C 编程的书,它对随机数从顶部的较低值到底部的最大值进行排序。我遇到了嵌套循环,试图弄清楚它是如何工作的,但我仍然不确定它是如何工作的。为什么变量的值为outter被分配给变量inner ?我知道第一个循环重复嵌套循环 8 次,因为 outter < 9 ,这对我来说毫无意义,因为数组由 10 个元素组成。我很困惑!所以outter我猜应该重复嵌套循环 9 次?或许 ?可能是!

for (inner = outer; inner < 10; inner++) { // << I don't understand this nested loop ? 
if (nums[inner] < nums[outer]) {
temp = nums[inner];
nums[inner] = nums[outer];
nums[outer] = temp;
didSwap = 1;
}
}

最佳答案

本质上,嵌套循环中的代码表示:

loop from the first element to the next-to-last element:

loop from the current value of the outer loop, to the last element,
looking for a smaller value than the one I am looking at in the outer loop.
if you find a smaller value, swap it into place.
if you didn't swap anything during this inner loop, exit; << BUG??

首先,我认为该算法有一个错误:内循环末尾的 didswap=0 条件仅意味着当前位置小于值在它下面;除非我误读了某些内容,否则并不意味着整个列表已排序,所以我认为这已经被破坏了。 (例如:如果您定义列表,使最小的元素从位置零开始,我认为整个事情都会退出而不会交换任何内容,无论列表的其余部分如何排序。但是,didswap是优化:无论如何,循环将在没有 did swap 标志的情况下终止,因此我现在将其完全删除并考虑主要算法。

但是让我们回顾一下这一点,了解其余代码在做什么: outer = inside 确保内部循环从外部循环当前所在的位置开始。 (所以:从第0个元素开始,从第0个元素循环到第10个元素,如果找到比当前元素0小的元素,就和第0个元素交换,继续查找。一旦内循环到了第10个元素,你就知道了元素 0 一定是整个列表中最小的元素,因为您与列表中的所有其他元素进行了比较。所以现在,我们查看位置 1 中的元素(outer=1)并与从位置 1 到位置的每个元素进行比较10、寻找比位置1小的元素,如果找到了,就交换元素,所以当我们完成内循环的第二遍时,我们知道位置1的元素是第二小的元素数组中的元素。然后我们继续查看第三个元素,依此类推。

注意:这里有一点效率低下:你可以从 inner = external+1 开始,因为 nums[i] < nuns[i] 永远不会成立,所以第一次迭代内循环被浪费了。但老实说,这种类型的效率非常低,以至于这种变化是在噪音中。还有许多更有效的排序算法,我确信稍后会在您的文本中介绍这些算法。

关于c - 这个嵌套循环的简单解释是什么,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21309963/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com