java一百题——7-5 比较大小

118 阅读2分钟

这是我参与11月更文挑战的第24天,活动详情查看:2021最后一次更文挑战

7-5 比较大小

本题要求将输入的任意3个整数从小到大输出。

输入格式:

输入在一行中给出3个整数,其间以空格分隔。

输出格式:

在一行中将3个整数从小到大输出,其间以“->”相连。

输入样例:

4 2 8
结尾无空行

输出样例:

2->4->8
结尾无空行

代码

使用交换函数

Java中没有地址的概念交换函数需要用到数组。

static int[] swap(int a,int b) {
    int temp=a;
    a=b;
    b=temp;
         return new int[] {a,b};
}

根据不同情况分别执行

if(a>b && a>c) {\
if(b>c) {\
swap=swap(a,c);\
a=swap[0];\
c=swap[1];\
}else {\
swap=swap(a,b);\
a=swap[0];\
b=swap[1];\
swap=swap(b,c);\
b=swap[0];\
c=swap[1];\
}\
\
}else if(a>b && a<c)// a只大于b -> 3 2 4\
{\
swap=swap(a,b);\
a=swap[0];\
b=swap[1];\
}else if(b>c)//b大于c->2 4 3\
{\
swap=swap(b,c);\
b=swap[0];\
c=swap[1];\
swap=swap(a,b);\
a=swap[0];\
b=swap[1];\
}\
st=a+"->"+b+"->"+c;\
System.out.print(st);\
}\

非优化代码

import java.util.Scanner;\
\
public class T05 {\
\
public static void main(String[] args) {\
Scanner sc=new Scanner(![]()System.in);\
int a=sc.nextInt();\
int b=sc.nextInt();\
int c=sc.nextInt();\
String st="";\
int[] swap;\
//a b c从小到大  ->a最大\
//b<c:4 1 2   b>c:4 2 1\
if(a>b && a>c) {\
if(b>c) {\
swap=swap(a,c);\
a=swap[0];\
c=swap[1];\
}else {\
swap=swap(a,b);\
a=swap[0];\
b=swap[1];\
swap=swap(b,c);\
b=swap[0];\
c=swap[1];\
}\
\
}else if(a>b && a<c)// a只大于b -> 3 2 4\
{\
swap=swap(a,b);\
a=swap[0];\
b=swap[1];\
}else if(b>c)//b大于c->2 4 3\
{\
swap=swap(b,c);\
b=swap[0];\
c=swap[1];\
swap=swap(a,b);\
a=swap[0];\
b=swap[1];\
}\
st=a+"->"+b+"->"+c;\
System.out.print(st);\
}\
\
static int[] swap(int a,int b) {\
int temp=a;\
a=b;\
b=temp;\
return new int[] {a,b};\
}\
}\

优化代码:使用ArrayList的类与Collections.sort方法自动排序

       ArrayList<Integer> arrayList = new ArrayList();
       Collections.sort(arrayList);

import java.util.ArrayList;
import java.util.Collections;
import java.util.Scanner;
public class Main {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        ArrayList<Integer> arrayList = new ArrayList();
        for(int i=0;i<3;i++){
            int num = sc.nextInt();
            arrayList.add(num);
        }
        Collections.sort(arrayList);
        for (int i = 0; i < 2; i++) { 
            System.out.print(arrayList.get(i)+"->");
        }
        System.out.println(arrayList.get(2));
    }
}

image.png