在list1中合并两个arraylist列表,同时保持排序
在我的任务中,第三步是调用方法合并来合并list1中的两个列表,以便list1 保持排序。
我编写我的代码,但它不能正常工作,输出显示错误,因为它很重要
public static void merge (ArrayList list1, ArrayList list2) { int i; int n=list1.size(); int pos , j=0; for (pos =0 ;pos<n ; pos++) { for ( i=0 ; ilist2.get(pos)) list1.add(pos,list2.get(pos)); else j++; } }
假设两个列表都已排序,您只需要一个for
循环:
public static void merge(List l1, List 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
未排序,则需要两个循环:
public static void merge(List l1, List 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; } } } }
public static void merge (ArrayList list1, ArrayList list2) { list1.addAll(list2); Collections.sort(list1); }
轻松修复:事后排序。
list1.addAll(list2); Collections.sort(list1);
使用集合可以避免重复。
合并列表后,调用sort方法如下。
Collections.sort(list1); // carries out natural ordering.
如果需要自定义排序,请使用Comparator对象
Collections.sort(list1, comparatorObject);
有关详细信息,请查看Comparator示例 。
这是您修改后的代码:
public static void merge (ArrayList list1, ArrayList list2) { list1.add(list2); //merges list 2 to list1 Collections.sort(list1); //natural ordering }
如果输入列表不是太长,我建议只合并列表并使用Collections.sort()
方法恢复顺序:
public static void mergeAndSort(List list1, List list2) { List combinedList = new ArrayList (list1); combinedList.addAll(list2); Collections.sort(combinedList); return combinedList; }
作为旁注,您应该尽可能使用List
接口而不是ArrayList
实现类。
public list mergeAndSort(List list1, List list2){ List list3; int list2Size = list2.size(); for(int i=0;i list2(j)){ small = list2(j; } } list3.add(small); //Smallest 1 will be added to the new list }
}
ArrayList a = new ArrayList(); ArrayList b = new ArrayList(); ArrayList c = new ArrayList(); a.add(1); a.add(3); a.add(5); a.add(7); a.add(17); a.add(27); a.add(37); b.add(0); b.add(2); b.add(4); while( a.size() > 0 || b.size() >0){ if( a.size() == 0 || b.size() == 0){ c.addAll(b); c.addAll(a); break; } if(a.get(0) < b.get(0)){ c.add(a.get(0)); a.remove(0); } else{ c.add(b.get(0)); b.remove(0); } } System.out.println(c.toString());