Swapping the values of two variables

        /// <summary>
        /// Swapping the values of two variables by 3 different ways
        /// </summary>
        /// <param name="args"></param>
        static void Main(string[] args)
        {
            int a = 0;
            int b = 1;
            Swap1(ref a, ref b);
            Console.WriteLine("a = {0}, b = {1}", a, b);

            Swap2(ref a, ref b);
            Console.WriteLine("a = {0}, b = {1}", a, b);

            Swap3(ref a, ref b);
            Console.WriteLine("a = {0}, b = {1}", a, b);

            Console.ReadKey();
        }

        /// <summary>
        /// With temp variable
        /// </summary>
        /// <param name="a"></param>
        /// <param name="b"></param>
        private static void Swap1(ref int a, ref int b)
        {
            if (a != b)
            {
                int temp = a;
                a = b;
                b = temp;
            }
        }

        /// <summary>
        /// By subtraction
        /// </summary>
        /// <param name="a"></param>
        /// <param name="b"></param>
        private static void  Swap2(ref int a, ref int b)
        {
            if (a != b)
            {
                a = a + b;
                b = a – b;
                a = a – b;
            }
        }

        /// <summary>
        /// XOR swap algorithm
        ///
        /// a       0 1 0 1
        /// b       0 0 1 1
        /// result  0 1 1 0
        /// </summary>
        /// <param name="a"></param>
        /// <param name="b"></param>
        private static void Swap3(ref int a, ref int b)
        {
            if (a != b)
            {
                a = a ^ b;
                b = a ^ b;
                a = a ^ b;
            }
        }

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s