Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to rotate elements to the left in array?

Tags:

c++

I'm trying to rotate an array to the left, for example rotateLeft3([1, 2, 3]) → [2, 3, 1]

Here is my solution, but it's not working for some reason. Can someone please explain what am I doing wrong ?

#include <iostream>

using namespace std;

int main()
{
    bool six;
    int Array[3] = { 1,2,3 };
    int x = sizeof(Array) / sizeof(Array[0]);
    int temp = Array[0];
    int temp2;
    for (int i = 0; i < x; i++)
    {
        Array[i] = Array[i + 1];
        Array[x - 1] = temp;
    }
    for (int i = 0; i < 3; i++)
    {
        cout << Array[i] << endl;
    }
    system("pause");

    return 0;
}
like image 509
Leo Bogod Avatar asked Sep 14 '16 10:09

Leo Bogod


1 Answers

This will be right approach. So do following changes in your code,
1) Change the Loop Condition to end (x-1) (otherwise it will be out of bound)
2) Remove the temp assignment inside loop
3) Assign value after the loop ends.

int temp = Array[0];
for (int i = 0; i < x-1; i++){
    Array[i] = Array[i + 1];
}
Array[x-1] = temp;

OR
if you want to use inbuilt template then use std::rotate in algorithm header

like image 58
sinsuren Avatar answered Sep 29 '22 06:09

sinsuren