2

I want to shift elements in one array to right by only changing the index. Also I don't want to use built-in functions

For example, if we have

8,6,5,3,9

Then We will have

9,8,6,5,3

If the array doesn't have enough length. the rest of the elements shift will start from the first index of array.

   int index = 0, temp = 0;
        int[] myarray = new int[int.Parse(Console.ReadLine())];
        for (int i = 0; i < myarray.Length; i++)
        {
            myarray[i] = int.Parse(Console.ReadLine());
        }

        for (int i = 0; i < myarray.Length; i++)
        {
            if (myarray.Length <= i + 5)
            {
                index = ((i + 5) % 5);
                temp = myarray[index];
                myarray[index] = myarray[i];
                myarray[i] = temp;
            }
            else
            {
                temp = myarray[i + 5];
                myarray[i + 5] = myarray[i];
                myarray[i] = temp;
            }
        }

this is what i have tried but its not working

Shervin Ivari
  • 1,759
  • 5
  • 20
  • 28
  • It would be nice if you describe your algorithm and elaborate on *"it's not working"*. Few comments in source may suffice. – Sinatr Nov 07 '19 at 09:08
  • Your example is one shift right. – Guy Nov 07 '19 at 09:12
  • @Guy If the array doesn't have enough length. the rest of the elements shift will start from the first index of an array.For example six shift 2 from last and 3 from first. – Shervin Ivari Nov 07 '19 at 09:14
  • @Sherviniv yes, this is how it works. But shift by 5 will leave an array with size 5 the same. – Guy Nov 07 '19 at 09:17
  • @Sinatr I filled my array in first for.Then i tried to change index with secound for.if the next index + 5 was more than the length of the array do something.I dont have no idea to how implement it. – Shervin Ivari Nov 07 '19 at 09:18
  • @Guy So this is the hard point I don't want to use another array to keep old values. but if you know a way with temp variable its ok – Shervin Ivari Nov 07 '19 at 09:21

1 Answers1

1

If shift count is less than or equal array size you can use this code (I edited answer by this link):

        using System;

        int M = 5;//shift count
        int size; //size of array
        int[] myarray = new int[int.Parse(Console.ReadLine())];
        for (int i = 0; i < myarray.Length; i++)
        {
            myarray[i] = int.Parse(Console.ReadLine());
        }

        size = myarray.Length;
        if (size >= M)
        {
            Array.Reverse(myarray, 0, size);
            Array.Reverse(myarray, 0, M);
            Array.Reverse(myarray, M, size - M);

            for (int i = 0; i < myarray.Length; i++)
            {
                Console.Write(myarray[i]+"\t");
            }

            Console.Read();
         }
Amir Azad
  • 113
  • 5