Q1. Can you write an algorithm to swap two values? A1.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
package algorithms; public class Swap { public static void main(String[ ] args) { int x = 5; int y = 6; //store 'x' in a temp variable int temp = x; x = y; y = temp; System.out.println("x=" + x + ",y=" + y); } } |
Swapping without a temp variable
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
package algorithms; public class Swap { public static void main(String[ ] args) { int x = 5; int y = 6; //without using a temp variable x = x + y; // 11 y = x - y; // 5 x = x - y; //6 System.out.println("x=" + x + ",y=" + y); } } |
Note: also try with * and \ Using bitwise “xor”
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
package algorithms; public class Swap { public static void main(String[ ] args) { int x = 5; int y = 6; //without using a temp variable //^ is xor 0 ^ 0 = 0, 0 ^ 1 = 1, 1 ^ 0 = 1, 0 ^ 0 = 0 x = x ^ y; // 3 y = x ^ y; // 5 x = x ^ y; //6 System.out.println("x=" + x + ",y=" + y); } } |
Q2. Can you write code to bubble sort { 30, 12,…