# 合并list1中的两个数组列表，同时保持排序。[英] merge two arraylist lists in list1 while it remain 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))
else
j++;
}
}
```

## 推荐答案

```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)) {
}
}
}
```

```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)) {
break;
}
}
}
}
```

## 其他推荐答案

```list1.addAll(list2);
Collections.sort(list1);
```

## 其他推荐答案

```public static void merge (ArrayList<Integer> list1, ArrayList<Integer> list2)
{
Collections.sort(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))
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)) {
}
}
}
```

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)) {
break;
}
}
}
}
```

## 其他推荐答案

Easy fix: sort afterwards.

```list1.addAll(list2);
Collections.sort(list1);
```

Use sets to avoid duplicates.

## 其他推荐答案

```public static void merge (ArrayList<Integer> list1, ArrayList<Integer> list2)
{