Q1. Can you write an algorithm in Java to swap two variables? A1.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
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); } } |
Q2. Can you write an algorithm to bubble sort the following array { 30, 12, 18, 0, -5, 72, 424 }?? A2.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 |
import java.util.Arrays; public class BubbleSort { public static void main(String[ ] args) { Integer[ ] values = { 30, 12, 18, 0, -5, 72, 424 }; int size = values.length; System.out.println("Before:" + Arrays.deepToString(values)); for (int pass = 0; pass < size - 1; pass++) { for (int i = 0; i < size - pass - 1; i++) { // swap if i > i+1 if (values[i] > values[i + 1]) swap(values, i, i + 1); } } System.out.println("After:" + Arrays.deepToString(values)); } private static void swap(Integer[ ] array, int i, int j) { int temp = array[i]; array[i] = array[j]; array[j] = temp; } } |
Q3. Is there…