Skip to content

Latest commit

 

History

History
38 lines (24 loc) · 873 Bytes

Ex_1_1_26.md

File metadata and controls

38 lines (24 loc) · 873 Bytes
title date draft tags categories
算法4 Java解答 1.1.26
2019-03-02 19:38:48 +0800
false
JAVA
技术
归档

1.1.26

问题:

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三个数变成有序。

参考: