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

前端 未结 2 1749
情书的邮戳
情书的邮戳 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条回答
  •  萌比男神i
    2021-01-19 18:39

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

    #include
    
    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;
    }
    

提交回复
热议问题