CodeIsland
CodeIsland

Reputation: 61

Simple swap on array in java gives strange result

this is such an easy piece of code. But still the result is wrong and I just do not see why - does anyone?

With the array int[] a = {3,1,0,2,5} and calling it with System.out.println(Arrays.toString(s.swap(a, a[0], a[1]))); I get [3, 2, 0, 1, 5] as result. What is happening here? I expect [1, 3, 0, 2, 5]. - Thanks!

import java.util.Arrays;


    public class MyClass {


    public int[] swap(int[] array, int a, int b){
            int temp = array[a];
            array[a] = array[b];
            array[b] = temp;
            return array;
        }
}

Upvotes: 0

Views: 61

Answers (4)

Lahcen YAMOUN
Lahcen YAMOUN

Reputation: 691

The function expect indices, but you're passing values ! Just consider System.out.println(Arrays.toString(s.swap(a, 0, 1))); instead of System.out.println(Arrays.toString(s.swap(a, a[0], a[1])));

Upvotes: 0

aschoerk
aschoerk

Reputation: 3593

temp becomes array[a[0]], array[3] --> 2

array[a[0]] array[3] becomes array[a[1]] becomes array[1]: --> 1

array[1] becomes 2

3 2 0 1 5

Upvotes: 0

Demilade
Demilade

Reputation: 513

The second and third parameters should be the index of your arrays you want to swap.

int[] a = {3,1,0,2,5}
to swap first and second index you should call swap(a, 0, 1)
swap(a, 0, 1)
Then a becomes{1,3,0,2,5}

Upvotes: 1

Bobby Tables
Bobby Tables

Reputation: 301

This line is calling swap with indices A[0]=3 and A[1]=1, thus swapping A[3] with A[1].

System.out.println(Arrays.toString(s.swap(a, a[0], a[1]))); 

Upvotes: 1

Related Questions