我正在学习递归我试图通过合并2个排序列表来返回排序列表并且迷路了。我知道这已经不正确,但任何指导都会有所帮助。
public static ArrayList<Integer> mergeMyList(ArrayList<Integer> list1,
ArrayList<Integer> list2)
{
ArrayList<Integer> tempList = null;
int n = list1.size() +list2.size();
int l = list2.size();
if ( n == 0 && l == 0)
{
tempList = list1;
return tempList;
}
if ( n == 0 )
{
tempList = list2;
return tempList;
}
if ( l == 0)
{
tempList = list1;
return tempList;
}
else
{
int x = list1.get(0);
int y = list2.get(0);
if (x < y )
{
// list1.add(x);
// list1.add(y);
tempList=list1;
// list1.remove(0);
// list2.remove(0);
}
else
{
list1.add(y);
tempList = list1;
list1.remove(0);
list2.remove(0);
tempList = mergeMyList(list1,list2);
}
}
tempList = mergeMyList(list1,list2);
return tempList;
}
答案 0 :(得分:0)
可以做短或更好,但我认为可以理解。
ArrayList<Integer> mergeList(ArrayList<Integer> list1,
ArrayList<Integer> list2)
{
ArrayList result = new ArrayList<Integer>();
while (list1.size() > 0 && list2.size() > 0)
{
if (list1.get(0) < list2.get(0))
result.add(list1.remove(0));
else
result.add(list2.remove(0));
}
while (list1.size() > 0) result.add(list1.remove(0));
while (list2.size() > 0) result.add(list2.remove(0));
return result;
}
ArrayList<Integer> QuickSort(ArrayList<Integer> list)
{
if (list.size() < 2)
return list;
ArrayList<Integer> left = list.subList(0, list.szie() / 2);
ArrayList<Integer> right = list.subList(list.szie() / 2, 8);
return mergeList(QuickSort(left), QuickSort(right));
}
这是一个递归的快速排序的完整示例。它很快(种类),但需要大量空间,如果列表太大,可能会溢出堆栈。
递归合并:
ArrayList<Integer> mergeList(ArrayList<Integer> list1,
ArrayList<Integer> list2)
{
if (list1.size() == 0) return list2;
if (list2.size() == 0) return list1;
ArrayList result = new ArrayList<Integer>();
if (list1.get(0) < list2.get(0))
result.add(list1.remove(0));
else
result.add(list2.remove(0));
result.addAll(mergeList(list1, list2));
return result;
}