0

I used LinkedList as a dymanic array then this array contains strings that need to be sorted in alphabetical order by using merge sort algorithm, which is added in the method and it turned out not working. Any suggestions?

public static LinkedList<String> merge(LinkedList<String> linkedList, LinkedList<String> linkedList2) {
        LinkedList<String> result = new LinkedList<String>();
        if(linkedList.size() == 0)
            result.add(linkedList2.remove());
        else if (linkedList2.size() == 0)
            result.add(linkedList.remove());

        for(int i=0; i<linkedList.size(); i++) {
            if(linkedList.get(i).compareTo(linkedList2.get(i)) < 0)
                result = linkedList;
            else
                result = linkedList2;
        }

        return result;
    }

1 Answer 1

1

The logic is wrong here, see comments for right logic:

    while(0 < linkedList.size() || 0 < linkedList2.size())
        if(0 == linkedList.size())        // if linkedList is empty
            result.add(linkedList.remove());        // should add head of linkedlist2 to result
        else if (0 == linkedList2.size())        // vice
            result.add(linkedList2.remove());       // versa
        else {
            linkedList.get(0).compareTo(linkedList2.get(0));      // else add the smaller of the two; you are just comparing, not adding the smaller
        }
Sign up to request clarification or add additional context in comments.

1 Comment

Your loop was fine, but the logic needed correction. Now the logic for the empty cases are right, but you need to move them back into the while loop again. Consider: if one of the list is empty the we need to add ALL OF THE OTHER list into the merged one. And the compare case is wrong - you need to add the smaller elements from the lists one at a time.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.