Algorithm requirements:
Set the n (n> 1) integer to be stored in the one-dimensional array R. Design an algorithm that is as efficient as possible in terms of time and space. Shift the sequence loop in R to the left position of P (0 <p <n), that is
(X0, X1 ,......, Xn-1) to (XP, XP + 1 ,..., Xn-1, x0, X1 ,..., Xp-1) requirements:
(1) give the basic design idea of the algorithm.
(2) According to the design philosophy, the C, C ++ or Java language is used to describe the algorithm, and the key points are annotated.
(3) Describe the time complexity and space complexity of the algorithm you designed.
Recursive Method (let's call this method)
# Define n 15 </P> <p> # include <iostream> </P> <p> using namespace STD; </P> <p> void Zuoyi (INT arr [], int start, int p) // number of shifts left <br/>{< br/> int behind, front = start; <br/> int temp = arr [Front]; </P> <p> while (P) <br/>{< br/> behind = front + P; <br/> If (behind> = N) <br/> behind-= N; <br/> // cout <front <Endl; <br/> If (behind = Start) <br/> break; </P> <p> arr [Front] = arr [behind]; <br/> front = behind; </P> <p >}< br/> arr [Front] = temp; </P> <p >}</P> <p> int main () <br/>{< br/> int arr [N]; <br/> cout <"initialization :"; <br/> for (INT I = 0; I <n; I ++) <br/>{< br/> arr [I] = I; <br/> cout <arr [I] <""; <br/>}< br/> cout <Endl; </P> <p> int P = 10, start = 0; </P> <p> If (N % P! = 0) <br/>{< br/> Zuoyi (ARR, start, P ); <br/>}< br/> else <br/> for (I = 0; I <p; I ++) <br/> Zuoyi (ARR, I, p); </P> <p> for (I = 0; I <n; I ++) <br/>{< br/> cout <arr [I] <""; <br/>}< br/> cout <Endl; </P> <p> return 0; <br/>}
Flip method:
# Define n 15 </P> <p> # include <iostream> </P> <p> using namespace STD; </P> <p> /******************************** **************************************** * ***************** <br/> flip method: <br/> first, flip the first P elements of the array, and then flip the next N-P elements, then, the entire element is flipped <br/> ******************************* **************************************** * ******************/<br/> void swap (INT arr [], int begin, int end) <br/>{< br/> int temp; <br/> while (begin <End) <br/>{< br/> temp = arr [begin]; <br/> arr [begin] = arr [end]; <br/> arr [end] = temp; <br/> begin ++; <br/> end --; <br/>}</P> <p> int main () <br/>{< br/> int arr [N]; <br/> cout <"initialization:"; <br/> for (INT I = 0; I <n; I ++) <br/>{< br/> arr [I] = I; <br/> cout <arr [I] <""; <br/>}< br/> cout <Endl; </P> <p> int P = 10, start = 0; </P> <p> // flip method <br/> swap (ARR, 0 P-1); <br/> swap (ARR, P, N-1 ); <br/> swap (ARR, 0, N-1); </P> <p> for (I = 0; I <n; I ++) <br/>{< br/> cout <arr [I] <""; <br/>}< br/> cout <Endl; </P> <p> return 0; <br/>}