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]
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!
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.