V
V
Vadim kyklaed2018-03-22 16:33:33
C++ / C#
Vadim kyklaed, 2018-03-22 16:33:33

Is there a difference between the two functions?

Hello, is there any difference between the two functions? how long do they take to complete?
I wrote the first one, I found the second one on the Internet, the point is to cyclically shift the elements in the array by a certain step.
my function is the first there, I use additional memory - I couldn’t think of a better option

#include <iostream>
using namespace std;

void rotate(int a[], unsigned size, int shift)
{
    int b[size]={};
  	if (shift> size){
  		shift=size;   
  }
  for (int i=shift;i<size;i++){
      b[i - shift]=a[i];    
          } 
  for (int i=size-shift;i<size;i++){
    b[i]=a[i-(size-shift)];
  }
  a=b;
    for (int i=0;i<size;i++){
    cout<<b[i]<<" ";
  }
  
}

void rotate2(int a[], unsigned size, int shift){
  
  int temp;
    for (int i = 0, j; i < shift; ++i)
    {
        temp = a[0];
        for (j = 0; j < size - 1; ++j)
            a[j] = a[j + 1];
        a[j] = temp;
    }
     for (int i=0;i<size;i++){
    cout<<a[i]<<" ";
  }
}




int main(){
  int shift = 7;
  unsigned size = 7;
  int a[size]={1,2,3,4,5,6,7};
  
  rotate2(a, size , shift);
  return 0;
}

Answer the question

In order to leave comments, you need to log in

1 answer(s)
R
Roman, 2018-03-22
@kyklaed

don't reinvent the wheel)))
STL library
use std::vector
and std::rotate
definition and example
en.cppreference.com/w/cpp/algorithm/rotate

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question