[英]How to add element at a specific position in ArrayList while sorting using Arraylist?
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. 我想在ArrayList中的特定位置添加一个整数值,但是这样做之后它会将最后一个元素压入其下一个索引,因为我在进行排序,我不希望它发生。 Help me with a snippet of code to write bubble sort using ArrayList. 使用一段代码帮助我使用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] 并且在传递ArrayList [23,54,67,4,5]之后
I get this as output: [4, 23, 23, 4, 54, 54, 4, 67, 67, 4, 5] 我将其作为输出:[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. 如果您查看ArrayList类的Javadocs ,那么有些方法将对您有所帮助。 I'd take a look at the set method! 我来看看set方法!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.