| title | 算法4 Java解答 1.1.26 | ||
|---|---|---|---|
| date | 2019-03-02 19:38:48 +0800 | ||
| draft | false | ||
| tags |
|
||
| categories |
|
Sorting three numbers. Suppose that the variables a, b, c, and t are all of the same numeric primitive type. Show that the following code puts a, b, and c in ascending order:
证明以下代码能将abc三个数以升序排列
(1) if (a > b) { t = a; a = b; b = t; }
(2) if (a > c) { t = a; a = c; c = t; }
(3) if (b > c) { t = b; b = c; c = t; }代码中第1行和第2行调整了原始三个数中第一个数字的位置,使得第一个位置是最小的数。
接下来第3行,调整第二个和第三个数的位置,通过比较使得第二个位置上的数字小于第三个位置上的数字。
执行完1,2,3行后,abc三个数变成有序。