0

I want to add an integer value at a specific position in an ArrayList but after doing so it pushes at last element to its next index, as i am doing sorting i do not want it to happen. Help me with a snippet of code to write bubble sort using ArrayList.

My code

void bubble_sorting(ArrayList<Integer> arr){
    int swap;
    for(int i=0;i<5-1;i++){
        for(int j=0;j<5-i-1;j++){
            if(arr.get(j)>arr.get(j+1)){
                swap = arr.get(j);
                arr.add(j,arr.get(j+1));
                arr.add(j+1,swap);
            }
        }
    }
}

and after passing ArrayList [23,54,67,4,5]

I get this as output: [4, 23, 23, 4, 54, 54, 4, 67, 67, 4, 5]

4
  • A quick look at the Javadoc for array list would help you out - docs.oracle.com/javase/8/docs/api/java/util/… Commented Feb 11, 2019 at 19:18
  • I'm pretty sure .add() is wrong. This inserts an element, not replaces it. Read the Java doc, and I think the method you want is .set(). Commented Feb 11, 2019 at 19:18
  • Possible duplicate of Add object to ArrayList at specified index Commented Feb 11, 2019 at 19:19
  • @markspace Thank you..and sorry to bother you all for my foolishness. Commented Feb 11, 2019 at 19:23

1 Answer 1

0

If you take a look at the Javadocs for the ArrayList class, there are some methods that will be helpful for you. I'd take a look at the set method!

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.