Java Bitwise Operators switch two variables without using temp variable

Question

We would like to write a program that prompts the user to enter three integers and display the integers in non-decreasing order without using the Java's sort() method.


import java.util.Scanner;

public class Main {
   public static void main(String[] strings) {
      int num1;/*from  w  ww  .j  a  v a 2 s . c  o m*/
      int num2;
      int num3;

      // Grabbing input from user
      Scanner input = new Scanner(System.in);
      System.out.print("Enter three Integers: ");
      num1 = input.nextInt();
      num2 = input.nextInt();
      num3 = input.nextInt();
      input.close();

      //your code here
      
      System.out.println("Sorted Numbers: " + num1 + " " + num2 + " " + num3);
   }
}



import java.util.Scanner;

public class Main {
   public static void main(String[] strings) {
      int num1;
      int num2;
      int num3;

      // Grabbing input from user
      Scanner input = new Scanner(System.in);
      System.out.print("Enter three Integers: ");
      num1 = input.nextInt();
      num2 = input.nextInt();
      num3 = input.nextInt();
      input.close();

      if (num1 > num2) {
         num1 ^= num2;
         num2 ^= num1;
         num1 ^= num2;
      }

      if (num2 > num3) {
         num2 ^= num3;
         num3 ^= num2;
         num2 ^= num3;
      }

      if (num1 > num2) {
         num1 ^= num2;
         num2 ^= num1;
         num1 ^= num2;
      }
      System.out.println("Sorted Numbers: " + num1 + " " + num2 + " " + num3);
   }
}



PreviousNext

Related