2

I am making a sorting program using bubble sort. I want to display what the array looks like each iteration, so if the input is [5,4,3,2,1] I want it to display [4, 3, 2, 1, 5] in the first iteration

public static void main(String[] args) {
    Integer[] age = {5,4,3,2,1};
    //int[][] ef = new int[age.length][];
    ArrayList<Integer[]> fe = new ArrayList<Integer[]>();
    
    for(int i=0;i<2;i++)
    {
        for(int ii=1;ii<5;ii++)
        {
            //System.out.println(Arrays.toString(age));
            if(age[ii]<age[ii-1])
            {
                int x = age[ii];                    
                age[ii]=age[ii-1];
                age[ii-1]=x;
            }
        }
        
        System.out.println("result "+Arrays.toString(age)+"\n");
        fe.add(age);                            
    }
    //System.out.println(Arrays.toString(age));
    for(Integer[] f : fe)
    {
        System.out.print(Arrays.toString(f));
    }
}

The output i want is [4, 3, 2, 1, 5][3, 2, 1, 4, 5]

Instead I get [3, 2, 1, 4, 5][3, 2, 1, 4, 5]

1
  • 1
    You put the same array in your list twice. If you want two different arrays in your list, you need to create two different arrays. Commented Sep 8, 2021 at 15:47

2 Answers 2

2

You need to make a copy of the array instead of adding the same reference multiple times.

fe.add(age.clone());
Sign up to request clarification or add additional context in comments.

2 Comments

@BryxterBulisig Happy to help.
This solution is based on a very important concept. @BryxterBulisig - It's important that you understand the concept instead of focussing on just making it work.
1

Your algorithm modifies age in place - you never create a copy of the array. In Java, any non-primitive is not stored by value but by reference, so fe contains several references to the same array.

1 Comment

Ohh i see, now I know why it does that. Thanks!

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.