C/C++ - efficient method of rotating an array without using build-in functions (homework)

前端 未结 2 1725
情书的邮戳
情书的邮戳 2021-01-19 18:02

The task is to rotate left or rotate right a subarray of an array given number of times.

Let me explain this on an example:

  • lets data be an array.
相关标签:
2条回答
  • 2021-01-19 18:34

    There's a trick to this. It's pretty weird that you'd get this for homework if the trick wasn't mentioned in class. Anyway...

    To rotate a sequence of N elements left by M:

    • reverse the whole sequence
    • reverse the last M elements
    • reverse the first N-M elements

    done

    e.g. left by 2: 1234567 -> 7654321 -> 7654312 -> 3456712

    0 讨论(0)
  • 2021-01-19 18:39

    Here is my code, it makes exactly n reads and n writes, where n is subarray size.

    #include<iostream>
    
    int arr[]= { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
    
    // replacing 'addr( pos, from, size )' with just 'pos' mean rotation the whole array
    int addr( int ptr, int from, int size)
    {
      return (ptr + from ) % size;
    }
    
    void rotate( int* arr, int shift, int from, int count, int size)
    {
      int i;
      int pos= 0;
      int cycle= 0;
      int c= 0;
      int c_old= 0;
      // exactly count steps
      for ( i=0; i< count; i++ ){
        // rotation of arrays part is essentially a permutation.
        // every permutation can be decomposed on cycles
        // here cycle processing begins
        c= arr[ addr( pos, from, size )  ];
        while (1){
          // one step inside the cycle
          pos= (pos + shift) % count;
          if ( pos == cycle )
            break;
          c_old= c;
          c= arr[ addr( pos, from, size )  ];
          arr[ addr( pos, from, size ) ]= c_old;
          i++;
        }
        // here cycle processing ends
        arr[ addr( pos, from, size ) ]= c;
        pos=   (pos   + 1) % count;
        cycle= (cycle + 1) % count;
      }
    }
    
    int main()
    {
      rotate( arr, 4, 6, 6, 11 );
      int i;
      for ( i=0; i<11; i++){
        std::cout << arr[i] << " ";
      }
      std::cout << std::endl;
      return 0;
    }
    
    0 讨论(0)
提交回复
热议问题