开发者

Java recursively print array in reverse

开发者 https://www.devze.com 2023-04-09 02:56 出处:网络
The array is an array of strings. The array is {\"hello\", \"how\", \"are\", \"you\", \"?\"} It sort of works, but the output mixes up the last 2 elements, and when I run my program the output comes

The array is an array of strings. The array is {"hello", "how", "are", "you", "?"}

It sort of works, but the output mixes up the last 2 elements, and when I run my program the output comes out as you ? are how hello, it should be ? you are how hello.

I put in a print statement to see what my left and right are and if开发者_开发知识库 they switch, but that didn't help since they only printed out the start values and nothing else.

Why is it printing out wrong? Is it not doing the recursion?

This is my method. It has to be done with divide and conquer.

public void outrev() {
    outrev(0, a.length - 1);
}

private void outrev(int left, int right) {
    System.out.println("left a[" + left + "] is " + a[left]);
    System.out.println("right a[" + right + "] is " + a[right]);
    int mid;
    if (left > right) {
        //do nothing
    }
    else if (left == right) {
        System.out.print(a[left]);
    }
    else {
        mid = (left + right) / 2;
        outm(mid + 1, right);
        System.out.print(a[mid] + " ");
        outm(left, mid - 1);
    }
}


public void outrev()
{ 
    List<String> arr = Arrays.asList(a);
    outrev(arr);
} 

private void outrev(List<String> arr)
{

    System.out.println(arr.get(arr.size() - 1));
    if(arr.size() != 1){
        outrev(arr.subList(0, arr.size() - 1));
    }
}

You have to import

import java.util.Arrays; import java.util.List;

Dunno if that breaks your homework's rules. Notice out outrev calls itself, but stops calling itself once the list is one item in length? That is the primary tenant of recursion, i.e. a function that calls itself, and has a terminating condition. In your original code outrev isn't really calling itself; you are overloading outrev in one case however, but that is different than recursion -- unless outm, which you didn't define was intended to be a call to outrev.

You should also have this program check to make sure that the list isn't empty, as your teacher could throw that at you, and the code would fail in that case.

Remember, with recursion, it's best to think about in terms of: 1) What to do when I have zero items. 2) What to do when I have one item. 3) How to handle every other case where my list has more than one item.

0

精彩评论

暂无评论...
验证码 换一张
取 消