Java, recursively reverse an array

后端 未结 13 1137
悲&欢浪女
悲&欢浪女 2020-12-17 16:44

I haven\'t found anything with the specific needs of my function to do this, yes, it is for homework.

So I have:

public void reverseArray(int[] x) {
         


        
13条回答
  •  我在风中等你
    2020-12-17 17:30

    This is probably the easiest way, not the fastest, but probably the easiest.

    A whole program would look something like this:

    public static void main(String [] args)
    {
        BackwardsArray back = new BackwardsArray();
    }
    
    public BackwardsArray()
    {
        int [] a = {1,2,3,4,5,6,7,8,9};
        printBackwards(a);
    }
    
    void printBackwards( int [] b)
    {
        print(b,b.length-1);
    }
    
    void print(int [] b, int pos)
    {
        System.out.println(b[pos]); // prints last item
        if(pos != 0)
        {
            print(b,pos-1);
        }
    }
    

    Hope it helps!

提交回复
热议问题