001package algs11;
002import stdlib.*;
003
004public class XSwap {
005        public static void main (String[] args) {
006                {
007                        int x = 42;
008                        int y = 27;
009                        StdOut.format ("before x=%d y=%d\n" , x, y);
010                        swap1 (x, y);
011                        StdOut.format ("after  x=%d y=%d\n\n" , x, y);
012                }
013                {
014                        Integer x = Integer.valueOf (42);
015                        Integer y = Integer.valueOf (27);
016                        StdOut.format ("before x=%d y=%d\n" , x, y);
017                        swap2 (x, y);
018                        StdOut.format ("after  x=%d y=%d\n\n" , x, y);
019                }
020                {
021                        int[] a = new int[2];
022                        a[0] = 42;
023                        a[1] = 27;
024                        StdOut.format ("before x=%d y=%d\n" , a[0], a[1]);
025                        swap3 (a, 0, 1);
026                        StdOut.format ("after  x=%d y=%d\n\n" , a[0], a[1]);
027                }
028                {
029                        Integer[] a = new Integer[2];
030                        a[0] = Integer.valueOf (42);
031                        a[1] = Integer.valueOf (27);
032                        StdOut.format ("before x=%d y=%d\n" , a[0], a[1]);
033                        swap4 (a, 0, 1);
034                        StdOut.format ("after  x=%d y=%d\n\n" , a[0], a[1]);
035                }
036        }
037        static void swap1 (int a, int b) {
038                int t = a;
039                a = b;
040                b = t;
041        }
042        static void swap2 (Integer a, Integer b) {
043                Integer t = a;
044                a = b;
045                b = t;
046        }
047        static void swap3 (int[] a, int i, int j) {
048                int t = a[i];
049                a[i] = a[j];
050                a[j] = t;
051        }
052        static void swap4 (Object[] a, int i, int j) {
053                Object t = a[i];
054                a[i] = a[j];
055                a[j] = t;
056        }
057}