Array Loop Right Shift

Source: Internet
Author: User
Tags gcd greatest common divisor

The main idea of the topic is to move an element in an array of length n to the right by moving the M-bit (or, of course, to the left), such as the array {1, 2, 3, 4, 5} to the right by 3 bits and then to {3, 4, 5, 1, 2}.

 time Complexity O (N), Spatial complexity O (1) Solution:all we have to do is put each element in the position it should be in, such as the first example, 1 should be placed in the 4 position, put 1 put good, 4 there is no place, that 4 should be where, in the position of 2, and so on, you can put all the elements are put, and only put it once. It looks perfect, but if you think about it, you can come up with a counter-example, for example {1, 2, 3, 4, 5, 6, 7, 8, 9} Right Shift 3, 1 placed in 4 positions, 4 placed in 7 position, then 7 put back 1, this time a lap is finished, but only row 3 elements, the remaining 6 elements have not moved, how to do? Continue next chant, is 2, then 2, 5, 8 also lined up, continue 3, 6, 9, this time the next element is 1 (because 1 was placed in the position of 4), should stop, how the program will know stopped here, so think of greatest common divisor, 9 and 3 of greatest common divisor is 3, So the first 3 number of cycles can be, why the previous example only need to do once, because the number of elements (5) and the number of moving bits (3) coprime.

Source: >

    1. int gcd (int a,int b) {if (a ==0| | b ==0) {return a + B;} int T;while (b <0) {t = a% B;a = B;b = t;} return A;} voidShiftRight2 (int m,int n,int*a) {m%= n;if (M ==0) return;for (int i =0, _i = gcd (n, m); I < _i;++i) {int k = I;int T = a [K];d o{k = (k + m)% n;int TT = a[k];a[k]= t;t = TT;} while (k! = i);}}

        



From for notes (Wiz)



Array Loop Right Shift

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.