-2

I've written following code to reverse an int array, however, I could not see the result to be right. Any hint on this? Thanks!

The result is

[I@15db9742[I@15db9742[I@15db9742[I@15db9742[I@15db9742[I@15db9742[I@15db9742[I@

Which seems to be weird.

public class reverseArray {
public static void main(String[] args) {
    int[] array = {2, 4, 5, 7, 8, 9, 12, 14, 17, 19, 22, 25, 27, 28, 33, 37};
    reverse(array, 0, array.length - 1);
}

public static void reverse(int[] data, int low, int high) {

    if (low < high) {
        int temp = data[low];
        data[low] = data[high];
        data[high] = temp;
        reverse(data, low + 1, high - 1);
    }
    System.out.print(data);
 }
}
ketan
  • 19,129
  • 42
  • 60
  • 98
Steven Wu
  • 39
  • 1
  • 7
  • One thing is that you can't print out an array directly, because the toString() will give you the reference pointing to a location in memory, which is the weird output you are getting. One option is to print it out index by index. – Zarwan Aug 31 '15 at 04:25

1 Answers1

5

You are System.out.print is printing the array Object and not the array index value.

Use like below:-

System.out.print(data[low]);

You can do something like to print array:-

public static void main(String[] args) {
        int[] array = {2, 4, 5, 7, 8, 9, 12, 14, 17, 19, 22, 25, 27, 28, 33, 37};
        reverse(array, 0, array.length - 1);
        printArray(array);
    }

    public static void reverse(int[] data, int low, int high) {

        if (low < high) {
            int temp = data[low];
            data[low] = data[high];
            data[high] = temp;
            reverse(data, low + 1, high - 1);
        }
     }

    private static void printArray(int [] array){
        for(int i:array){
            System.out.print(i+"|");
        }
        System.out.println();
    }

Output: 37|33|28|27|25|22|19|17|14|12|9|8|7|5|4|2|
Amit Bhati
  • 5,569
  • 1
  • 24
  • 45
  • In case you do want to print the whole array, you can use `Arrays.toString(data)`. – Thilo Aug 31 '15 at 04:25
  • 2
    [**Should one advise on off-topic / duplicate questions?**](http://meta.stackoverflow.com/questions/276572/should-one-advise-on-off-topic-questions) All it does is encourage more bad behavior and teach new users the wrong lessons. – durron597 Aug 31 '15 at 04:29
  • i hope these example help you , public class Solution { static Integer[] c = {3, 2, 4, 1}; static Integer[] c1 = new Integer[3]; public static void main(String arg[]) { Arrays.sort(c); c1 = c; Arrays.sort(c, Collections.reverseOrder()); System.out.println(" Descending = "); for (int i = 0; i < c.length; i++) { System.out.println(+ c1[i]); } Arrays.sort(c); System.out.println("Ascending = " ); for (int number : c) { System.out.println( number); } } } – Sriram S Aug 31 '15 at 04:34