ObjecÂtive: – Given three integers, sort them without using if condition.
Appraoch:
- Say 3 integers are, a, b, c.
- Find the maximum of a, b, c using Max() function.
- multiply all integers by -1. Again find Minimum of -a, -b, -c using Max() function.
- Add the Max and Min from above steps and subtract it from (a+b+c). It will give you middle element.
Complete Code:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class Sorting3Integers { | |
// sort 3 given integers, sort them with out using if conditions | |
public void sort(int x, int y, int z){ | |
int max,mid,min; | |
max = Math.max(x,Math.max(y, z)); | |
min = –Math.max(–x,Math.max(–y, –z)); | |
mid = (x+y+z)–(max+min); | |
System.out.println("Sorted order " + min + " " + mid + " " + max); | |
} | |
public static void main(String[] args) { | |
int x = 4; | |
int y = 1; | |
int z = 9; | |
Sorting3Integers s = new Sorting3Integers(); | |
s.sort(x, y, z); | |
} | |
} |
Output:
Sorted order 1 4 9