当我编译合并排序时,它会编译罚款,但没有输出。
这需要递归完成。另外,我在main中运行了printList()函数,所以我忘记打印列表了。我在过去的30分钟里一直盯着这个。
public void printList(){
for(int i = 0; i < fullNames.size(); i++){
System.out.println(fullNames.get(i));
}
}
public void sort(){
fullNames = mergeSort(fullNames);
}
public ArrayList<String> extract(ArrayList<String> ex, int low, int high){
ArrayList<String> answer = new ArrayList<String>();
for(int i = low; i <= high; i++){
answer.add(ex.get(i));
}
return answer;
}
public ArrayList<String> merge(ArrayList<String> first, ArrayList<String> second){
int f = 0;
int s = 0;
ArrayList<String> answer = new ArrayList<String>();
while(first.size() > 0 || second.size() > 0){
if(s != second.size() && f != first.size()){
if(first.get(f).compareTo(second.get(s)) > 0){
answer.add(second.get(s));
s++;
}
else if(first.get(f).compareTo(second.get(s)) < 0){
answer.add(first.get(f));
f++;
}
}
else if(f == first.size()){
while(s != second.size()){
answer.add(second.get(s));
s++;
}
}
else{
while(f != first.size()){
answer.add(first.get(f));
f++;
}
}
}
return answer;
}
public ArrayList<String> mergeSort(ArrayList<String> names){
int k = names.size()-1;
if(k > 1){
ArrayList<String> first = extract(names, 0, k / 2);
ArrayList<String> second = extract(names, (k / 2) + 1, k);
mergeSort(first);
mergeSort(second);
return merge(first, second);
}
else{
return names;
}
}
答案 0 :(得分:1)
合并中的while条件永远不会为false,因为第一个和第二个的大小永远不会在循环中调整:
while(first.size() > 0 || second.size() > 0){
if(s != second.size() && f != first.size()){
if(first.get(f).compareTo(second.get(s)) > 0){
answer.add(second.get(s));
s++;
}
else if(first.get(f).compareTo(second.get(s)) < 0){
answer.add(first.get(f));
f++;
}
}
else if(f == first.size()){
while(s != second.size()){
answer.add(second.get(s));
s++;
}
}
else{
while(f != first.size()){
answer.add(first.get(f));
f++;
}
}
}