title: Rotate array left or right by a set number of positions in o(n) complexity
body: <p>I want to write a program that shifts an array by a set number of positions right or left based on the user's input (positive ->, negative &lt;-). The program has to have O(n) complexity. I've written it this way but it doesn't work as it should. In the example the output should be "2, 3, 4, 5, 6, 1" but in my version is "6, 2, 3, 4, 5, 1". </p>
  
  <pre><code>#include &lt;stdio.h&gt;
  #include &lt;string.h&gt;
  #include &lt;math.h&gt;
  
  void rotate(int *array, int N, int D);
  
  int main(){
      int i;
      int array[] = {1, 2, 3, 4, 5, 6};
  
      rotate(array, sizeof(array)/sizeof(int), 5);
  
      for(i=0; i&lt;sizeof(array)/sizeof(int); i++)
          printf("%d\t", array[i]);
  
      return 0;
  }
  
  void rotate(int *array, int N, int D){
      int i, j, *tmp, d;
  
      tmp = malloc(abs(D) * sizeof(int));
  
      if(D&lt;0){
          d = abs(D);
          for(i=d; i&lt;N; i++){
              tmp[i%d] = array[i];
              array[i] = array[i-d];
              array[i-d] = tmp[i%d];
          }
      }
      if(D&gt;0){
          for(i=(N-D-1); i&gt;=0; i--){
              tmp[i%D] = array[i];
              array[i] = array[i+D];
              array[i+D] = tmp[i%D];
          }
      }
  }
  </code></pre>
  
  <p>Thank you.</p>