Move array to K-bit right

Source: Internet
Author: User

Idea: the inverse algorithm * 3 times can be
First reverse the k-n-1.
Reverse the 0-k-1.
Overall reversal can be

//把数组循环右移K位public class Test_plus {    /*    *数组倒序算法,循环首尾互换    */    public static void reverse(int[] a,int b,int e) {        for(;b<e;b++,e--) {            int temp=a[e];            a[e]=a[b];            a[b]=temp;        }    }    public static void shift_k(int[] a,int k) {        int n=a.length;        //右移k位和右移n+k位等价        k=k%n;        //将倒数第k个和最后一个之间的数组段对换循环        reverse(a,n-k,n-1);        //将第一个和第倒数第k-1个数对换        reverse(a,0,n-k-1);        //将第一个数和最后一个数之间的数对换        reverse(a,0,n-1);    }    public static void main(String[] args) {        int array[]= {1,2,3,4,5,6,7,8};        shift_k(array, 2);        for(int i=0;i<array.length;i++) {            System.out.println(array[i]+"");        }    }}

Move array to K-bit right

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.