Swapping array elements

Generic C# code to swap consecutive and then alternate elements in an array.

using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

 

namespace Swap

{

    class Swap

    {

        static void Main(string[] args)

        {

            int[] array = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 0 };

            Console.WriteLine("Initial Array: ");

            for (int i = 0; i < array.Length; i++)

            {

                Console.Write(array[i] + " ");

            }

            Console.WriteLine();

            for (int j = 1; j < array.Length; j++)

            {

                for (int i = 0; i < array.Length – j; i++)

                {

                    int temp = array[i];

                    array[i] = array[i + j];

                    array[i + j] = temp;

                }

                Console.WriteLine("Array after " + j + " iteration(s)");

                for (int i = 0; i < array.Length; i++)

                {

                    Console.Write(array[i] + " ");

                }

                Console.WriteLine();

            }

        }

    }

}

 

Output:

Initial Array:

1 2 3 4 5 6 7 8 9 0

Array after 1 iteration(s)

2 3 4 5 6 7 8 9 0 1

Array after 2 iteration(s)

4 5 6 7 8 9 0 1 2 3

Array after 3 iteration(s)

7 8 9 0 1 2 3 5 6 4

Array after 4 iteration(s)

1 2 3 5 6 4 9 0 7 8

Array after 5 iteration(s)

4 9 0 7 8 1 2 3 5 6

Array after 6 iteration(s)

2 3 5 6 8 1 4 9 0 7

Array after 7 iteration(s)

9 0 7 6 8 1 4 2 3 5

Array after 8 iteration(s)

3 5 7 6 8 1 4 2 9 0

Array after 9 iteration(s)

0 5 7 6 8 1 4 2 9 3

Press any key to continue . . .

Advertisements
This entry was posted in Information Technology. Bookmark the permalink.

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 )

Google+ photo

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

Connecting to %s