在list1中合并两个arraylist列表,同时保持排序 [英] merge two arraylist lists in list1 while it remain sorted
本文介绍了在list1中合并两个arraylist列表,同时保持排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在我的作业中,第三步是调用方法合并来合并list1中的两个列表,以便list1 保持排序。
In my assignment the third step is to Call the method merge to merge the two lists in list1 so that the list1 remains sorted.
我编写了我的代码,但它运行不正常,输出显示错误,因为重要的是要排序
I write my code but it doesn't work well , the output show wrong because it important to be sorted
public static void merge (ArrayList<Integer> list1, ArrayList<Integer> list2)
{
int i;
int n=list1.size();
int pos , j=0;
for (pos =0 ;pos<n ; pos++)
{
for ( i=0 ; i<n ; i++)
if (list1.get(j)>list2.get(pos))
list1.add(pos,list2.get(pos));
else
j++;
}
}
推荐答案
你只需要一个用于
循环,假设两个列表都已排序:
You only need one for
loop assuming both lists are sorted:
public static void merge(List<Integer> l1, List<Integer> l2) {
for (int index1 = 0, index2 = 0; index2 < l2.size(); index1++) {
if (index1 == l1.size() || l1.get(index1) > l2.get(index2)) {
l1.add(index1, l2.get(index2++));
}
}
}
如果 l2
未排序,您需要两个循环:
If l2
isn't sorted, you need two loops:
public static void merge(List<Integer> l1, List<Integer> l2) {
for (int index2 = 0; index2 < l2.size(); index2++) {
for (int index1 = 0; ; index1++) {
if (index1 == l1.size() || l1.get(index1) > l2.get(index2)) {
l1.add(index1, l2.get(index2));
break;
}
}
}
}
这篇关于在list1中合并两个arraylist列表,同时保持排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文