Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
274 views
in Technique[技术] by (71.8m points)

3 numbers in ascending order WITHOUT the use of conditional statements in Java. As in I can't use if statements at all

My code looks like this so far:

public class ThreeSort {
    public static void main(String[] args) {

        int num1 = Integer.parseInt(args[0]);
        int num2 = Integer.parseInt(args[1]);
        int num3 = Integer.parseInt(args[2]);


        int x = Math.min(num1, num2);
        int min = Math.min(x,num3);
        int z = Math.max(num1, num2);
        int max = Math.max(z, num3);

        int a = 0;
        int mid = 0;



        while (mid >= min && mid <= max) {

        mid = a;

        }

        System.out.println(min);
        System.out.println(a);
        System.out.println(max);



    }

I know how to do the min and the max but I'm having troubles with the middle one. Any idea how to do that without conditional statements?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

in this case there is a simple algorithm for it:

mid = Math.max(Math.min(num1,num2), Math.min(Math.max(num1,num2),num3));

Also as the operator ^ denotes bitwise xor. so another way is:

mid=num1^num2^num3^max^min;

EXAMPLE:

public static void main(String[] args) {
    System.out.println(mid(70, 3, 10));
}

static int mid(int a, int b, int c) {
    int mx = Math.max(Math.max(a, b), c);
    int mn = Math.min(Math.min(a, b), c);
    int md = a ^ b ^ c ^ mx ^ mn;
    return md;
}

OUTPUT: 10.

Also as OldCurmudgeon said below you can calculate the mid with below formula:

int mid = num1 + num2 + num3 - min - max;

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...