Reputation:
When I compile my merge sort, it compiles fines but there is no output.
This needs to be done recursively. Also, I do run my printList() function in my main, so it isn't that I am forgetting to print the list. I've been staring at this for the past 30 minutes.
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;
}
}
Upvotes: 1
Views: 47
Reputation: 4065
The while condition in your merge will never be false because the size of first and second is never adjusted within the loop:
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++;
}
}
}
Upvotes: 1