题目描述
给出三个整数 a,b,c(0≤a,b,c≤100),要求把这三位整数从小到大排序。
输入格式
输入三个整数 a,b,c,以空格隔开。
输出格式
输出一行,三个整数,表示从小到大排序后的结果。
初始版本
import java.util.Scanner; public class Main{ public static void main(String[] arg){ Scanner sc = new Scanner(System.in); int a = sc.nextInt(); int b = sc.nextInt(); int c = sc.nextInt(); if(a<=b){ if(b<=c){ System.out.println(a+" "+b+" "+c); }else{ if(a<c){ System.out.println(a+" "+c+" "+b); }else{ System.out.println(c+" "+a+" "+b); } } }else{ if(b>c){ System.out.println(c+" "+b+" "+a); }else{ if(a>c){ System.out.println(b+" "+c+" "+a); }else{ System.out.println(b+" "+a+" "+c); } } } } }存在问题
虽然逻辑正确,但代码繁琐,可读性差
优化方案
方案一(依然只用if,简化版本):
不再写多层嵌套,用临时变量交换,保证 a ≤ b ≤ c,代码短、逻辑直白:
import java.util.Scanner; public class Main{ public static void main(String[] arg){ Scanner sc = new Scanner(System.in); int a = sc.nextInt(); int b = sc.nextInt(); int c = sc.nextInt(); int t; // 如果a比b大,交换a,b if (a > b) { t = a; a = b; b = t; } // 如果a比c大,交换a,c → a一定是最小值 if (a > c) { t = a; a = c; c = t; } // 最后保证b ≤ c if (b > c) { t = b; b = c; c = t; } System.out.println(a + " " + b + " " + c); } }✅ 优点:
- 没有地狱式嵌套 if,阅读轻松
- 改动一个数字也不容易出错
- 完全只用 if 判断,符合分支结构作业要求
方案二(数组 + 工具类排序)刷题、竞赛最优解:
把 3 个数放进数组,调用 Java自带排序函数(局限是只能从小到大排序),代码最少:
import java.util.Scanner; import java.util.Arrays; public class Main{ public static void main(String[] arg){ Scanner sc = new Scanner(System.in); int[] nums = {sc.nextInt(), sc.nextInt(), sc.nextInt()}; Arrays.sort(nums); System.out.println(nums[0] + " " + nums[1] + " " + nums[2]); } }✅ 优点:
- 以后如果不是 3 个数,是 100 个数,几乎不用改代码
- 逻辑干净,不会写错判断分支
方案三(Math.max/ Math.min 纯计算版)(趣味写法):
不用交换变量,直接算出最小、中间、最大值:
import java.util.Scanner; public class Main{ public static void main(String[] arg){ Scanner sc = new Scanner(System.in); int a = sc.nextInt(); int b = sc.nextInt(); int c = sc.nextInt(); int min = Math.min(Math.min(a,b),c); int max = Math.max(Math.max(a,b),c); int mid = a + b + c - min - max; System.out.println(min + " " + mid + " " + max); } }原理:三个数总和减去最大值、最小值,剩下的就是中间值,非常巧妙!