Algorithm to rotate an array in linear time

后端 未结 22 2096
我寻月下人不归
我寻月下人不归 2020-11-28 05:05

How to rotate an integer array by i times using swap function only in linear time.

22条回答
  •  遥遥无期
    2020-11-28 06:03

    /*
     * To change this template, choose Tools | Templates
     * and open the template in the editor.
     */
    package rotateinlineartime;
    
    /**
     *
     * @author Sunshine
     */
    public class Rotator {
    
        void reverse(int a[], int n) {
            for (int i = 0; i <= n - 1; i++) {
                int temp;
                temp = a[i];
                a[i] = a[n - 1];
                a[n - 1] = temp;
                n--;
            }
    
            printArray(a);
        }
    
        void printArray(int a[]) {
            for (int i = 0; i < a.length; i++) {
                System.out.println(a[i]);
            }
        }
    }
    

提交回复
热议问题