Everyone Is An Achiever

Wednesday, December 10, 2014

Reversing array in-place

8:53 PM Posted by Unknown No comments


In this tutorial, we will do actual reversing of the array elements without using an extra array.  Many programmer when they're asked to reverse an array they either display the array in reverse order, or use another array and copy the contents of array 1 to array 2 starting from the last position or they may use built-in methods such as Array.Reverse(array_name).

But, what if we want to do actual reversing to the array elements without using a built-in method or using a second array?
The idea to do that is to have two pointers:
-  The first pointer will point to the first element in the array
-  The second pointer will point to the last element in the array
-  Each time the loop runs, shift the item in the first position with the item in the last position, then increment the first pointer and decrement the pointer of the last position.

Here an example on how it will work:
You'll enter the size of the array and lets say it is: 10
Then you'll enter 10 element, assume they are:
3,5,4,7,6,1,8,9,2,10

iteration
elements that have been shifted
1st
10,5,4,7,6,1,8,9,2,3
2nd
10,2,4,7,6,1,8,9,5,3
3rd
10,2,9,7,6,1,8,4,5,3
4th
10,2,9,8,6,1,7,4,5,3
5th
10,2,9,8,1,6,7,4,5,3

Before:
3,5,4,7,6,1,8,9,2,10
After:
10,2,9,8,1,6,7,4,5,3

One important thing to mention here is that the loop that will do the shifting should iterate up to size_of_array / 2 (and this is clear in the table). The reason is that we shift 2 items in one iteration, so as for the above example we have 10 elements and we shift 2 elements each time so we need to iterate 5 times.
Here is the full CSharp code:




using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections.ObjectModel;

namespace TestConsole
{

    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Enter the size of the array");
            int n = int.Parse(Console.ReadLine());
            int[] array = new int[n];
            int decrementPointer = n - 1;
            int temp;

            Console.WriteLine("Enter the array elements");
            for (int i = 0; i < n; i++)
                array[i] = int.Parse(Console.ReadLine());

            Console.WriteLine("The array before reversing");
            for (int i = 0; i < n; i++)
                Console.Write(array[i] + " ");

            for (int i = 0; i < n / 2; i++)
            {
                temp = array[i];
                array[i] = array[decrementPointer];
                array[decrementPointer] = temp;

                decrementPointer--;
            }
            
            Console.WriteLine("\nThe array after reversing");
            for (int i = 0; i < n; i++)
                Console.Write(array[i] + " ");

            Console.ReadLine();
        }
    }
}


0 comments:

Post a Comment