Reverse an Integer Array without using extra space in C#

Our approach is to solve this problem without traversing whole array. So we keep two variables, one is set to start item of an array and another is set to end item of an array.and we move both of them simultaneously. So, in n/2 iterations we completely traverse the array.

Time complexity = O(n)

        static void Main(string[] args)
        {
            int[] arr = { 61, 19, 34, 83, 123, 97 };
            Reverse(arr);
            foreach (var item in arr)
            {
                Console.WriteLine(item);
            }
            Console.ReadKey();
        }

        static void Reverse(int[] arr)
        {
            if (arr.Length == 0 || arr.Length == 1)
            {
                return;
            }
            else
            {
                int start = 0, end = arr.Length - 1, temp = 0;
                while (start < end)
                {
                    temp = arr[end];
                    arr[end] = arr[start];
                    arr[start] = temp;
                    ++start;
                    --end;
                }
            }
        }
Advertisements

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