Algorithm-left rotation Array

Source: Internet
Author: User

Define the left rotation operation of the string: Move several characters before the string to the end of the string. For example, the string abcdef is rotated two places to the left to obtain the string cdefab. Idea: such as the left rotation of 2 places, first "reverse" The 2 places, then "reverse" the remaining N-2 bit, and finally "reverse" all N places.

 

The algorithm is as follows:

/// <Summary> <br/> // define the left rotation operation of the string: Move several characters before the string to the end of the string. <Br/> // If the string abcdef is left rotated by two digits, the string cdefab is obtained. <Br/> /// </Summary> <br/> // <Param name = "A"> Operation Array </param> <br/> // <param name = "N"> array length </param> <br/> // <Param name = "K"> Number of left-rotated digits </param> <br/> static void test (INT [], int N, int K) <br/>{< br/> K % = N; <br/> If (k = 0) return; </P> <p> reverse (A, 0, k-1); <br/> reverse (A, k, n-1 ); <br/> reverse (A, 0, n-1 ); <br/>}</P> <p> // <summary> <br/> // reverse <br/> /// </Summary> <br/> /// <Param name = "A"> Operation Array </param> <br/> /// <Param name = "begin"> reverse the start position </param> <br/> // <Param name = "end"> reverse the end position </param> <br/> static void reverse (INT [], int begin, int end) <br/>{< br/> while (begin <End) <br/>{< br/> int temp = A [end]; <br/> A [end] = A [begin]; <br/> A [begin] = temp; </P> <p> begin ++; <br/> end --; <br/>}< br/>}

The code is clear and concise.

End.

 

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.