1

I want to sort an array using the swap() method as shown in the code. I want to know how to pass the array and sort it.

    public class Test {
    public static void main(String[] args) {
        int [] ar = {9, 4, 5, 3, 1, 8, 4, 2, 0};
        System.out.println(Arrays.toString(ar));
        for (int i = 0; i<ar.length-1; i++){
            for (int j = i+1; j<ar.length; j++){
                swap(ar[i], ar[j]);
            }
        }
        System.out.println(Arrays.toString(ar));
    }
    private static void swap(int i, int j) {
        int temp;
        if(i>j){
            temp = j;
            j = i;
            i= temp;
        }       
    }
}
JavaHopper
  • 5,567
  • 1
  • 19
  • 27
Eid
  • 190
  • 3
  • 14
  • 5
    You declare a method parameter of array type: `int[] ar`. – Andy Turner Jul 27 '16 at 20:37
  • You mean I have to declare it like:private static void swap(int [], int []){...} – Eid Jul 27 '16 at 20:40
  • No, you add a *third* parameter for the array – OneCricketeer Jul 27 '16 at 20:40
  • You don't have to make a special treatment to a variable if you want to pass it by reference. This is not like C/C++, you just passe the variable as it is. Read : [Is java pass by value or by reference](http://stackoverflow.com/questions/40480/is-java-pass-by-reference-or-pass-by-value) – Yassin Hajaj Jul 27 '16 at 20:40
  • I don't know if this is intended or not but I believe your loop isn't looping through the whole array. Should be `i – Austin Jul 27 '16 at 20:41

2 Answers2

2

Arrays are just like any other type. If you want to pass an array to a method, declare a parameter of that type, e.g.

private static void swap(int[] ar, int i, int j) { ... }
                         ^ This is a parameter of type int[].

Note that the i and j you pass should be indexes, not values in the array:

swap(ar, i, j);

and swap the elements thus:

temp = ar[i];
ar[i] = ar[j];
ar[j] = temp;
Andy Turner
  • 137,514
  • 11
  • 162
  • 243
  • Thanks. It was useful. – Eid Jul 27 '16 at 20:47
  • @Eid you can also swap the 2 values without a temporary variable: `ar[i]^=ar[j]; ar[j]^=ar[i]; ar[i]^=ar[j];`. Which is a great story to tell when you're with your friends in a pub. But I wouldn't recommend it though. – bvdb Jul 28 '16 at 16:08
0

The easiest way would be:

private static void swap(int[] ar, int i, int j) {
    //Do work here
}
Susannah Potts
  • 837
  • 1
  • 12
  • 32