Skip to content

Array algorithms

Java for AP CS A Lesson 9 2:09 English narration · English + 中文 subtitles burned in

space play · ←/→ 5s · j/l 10s · f fullscreen · ,/. speed

Chapters

Transcript
Four array jobs turn up on nearly every paper, and they are all the same shape. 有四件数组上的活儿,几乎每张卷子都会出现,而它们的形状是一样的。
Sum: start at zero and add every value. 求和:从 0 开始,把每个值都加上去。
Count: start at zero and add one, but only when a test passes — here, only for even numbers. 计数:也从 0 开始,每次加 1,但只在某个条件成立时加—— 这里只对偶数加。
One variable, declared before the loop, changed inside it, and read afterwards. 一个变量,在循环之前声明,在循环里面改动,循环之后读取。
That sentence describes all four of them. 这一句话,把四件活儿全说清楚了。
Maximum keeps the best so far. 求最大值靠的是"保住目前为止最好的那个"。
Start it at the first element, then compare each one against it and replace when you find something bigger. 先把它设成第一个元素, 然后拿每一个去和它比,遇到更大的就换掉。
Watch the box: three, then nine, and nine survives the rest. 看那个盒子:先是 3,然后是 9,之后 9 一直守住了。
And here is the trap — start max at a zero, never at zero. 而陷阱在这里——把 max 设成 a ,绝不要设成 0。
An array of negative numbers would beat a zero start and give you a maximum that is not in the array. 一个全是负数的数组,会输给那个 0 起点, 让你得到一个根本不在数组里的"最大值"。
A search hands back a position, not a yes or no. 查找交还的是一个"位置",而不是"有"或"没有"。
Walk the indexes, and the moment you find the target, return i and stop. 沿着索引走, 一旦找到目标,就 return i 并且立刻停下。
If the loop finishes without finding it, return minus one. 如果循环走完了还没找到,就返回 -1。
Minus one is the convention because it is never a real index, so the caller can always tell the two apart. 用 -1 是个约定,因为它永远不会是一个真实的索引, 这样调用方总能把两种情况分开。
Average is sum divided by length, and it costs a mark every single year. 平均值就是总和除以长度,而它每一年都要吃掉一分。
Both sum and length are ints, so Java does integer division and throws the decimal away — twenty-five over four gives six, not six point two five. sum 和 length 都是 int, 所以 Java 做的是整数除法,把小数部分直接扔掉—— 25 除以 4 得到 6,而不是 6.25。
Declaring the answer as a double does not help, because the damage is already done. 把结果声明成 double 也救不了,因为损失早就发生了。
Cast one of them to double first, and the division is done properly. 先把其中一个转成 double,除法才会正确地做。
Four things to take with you. 带走四点。
One: all four keep one variable across the whole loop. 第一:这四种做法都靠一个贯穿整个循环的变量。
Two: start max at the first element, never at zero. 第二:max 的初值取第一个元素,绝不取 0。
Three: a search that finds nothing returns minus one. 第三:什么也没找到的查找,返回 -1。
Four: cast to double before dividing, or you lose the decimal. 第四:相除之前先转成 double,否则你会丢掉小数。
Now write the four algorithms below. 现在去下面把这四个算法写出来。

Log in or create account

IGCSE, A-Level & AP