合并 list1 中的两个 arraylist 列表,同时保持排序 [英] merge two arraylist lists in list1 while it remain sorted

查看:30
本文介绍了合并 list1 中的两个 arraylist 列表,同时保持排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的作业中,第三步是调用方法 merge 来合并 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++;
       } 
 }

推荐答案

假设两个列表都已排序,您只需要一个 for 循环:

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆