Java, recursively reverse an array

后端 未结 13 1103
悲&欢浪女
悲&欢浪女 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:32

    Here is the main method:

    package main;
    
    public class Main {
        public static void main(String[] args) {
            StringOps ops = new StringOps();
            String string = "Arjun";
            // reversing the string recrusively
            System.out.println(ops.reverseRecursively(string.toCharArray(), 0));
        }
    }
    

    and here is the recursive function:

    package main;
    
    public class StringOps {
        public char[] reverseRecursively(char[] array, int i) {
            char[] empty = new char[0];
            if (array.length < 1) {
                System.out.println("you entered empty string");
                return empty;
            }
            char temp;
            temp = array[i];
            array[i] = array[array.length - 1 - i];
            array[array.length - 1 - i] = temp;
            i++;
    
            if (i >= array.length - 1 - i) {
                return array;
            } else {
                reverseRecursively(array, i);
                return array;
            }
    
        }
    
    }
    

提交回复
热议问题