arrays - Merge Sort in String using LinkedList -
i used linkedlist dymanic array array contains strings need sorted in alphabetical order using merge sort algorithm, added in method , turned out not working. 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; }
the logic wrong here, see comments right logic:
while(0 < linkedlist.size() || 0 < linkedlist2.size()) if(0 == linkedlist.size()) // if linkedlist empty result.add(linkedlist.remove()); // should add head of linkedlist2 result else if (0 == linkedlist2.size()) // vice result.add(linkedlist2.remove()); // versa else { linkedlist.get(0).compareto(linkedlist2.get(0)); // else add smaller of two; comparing, not adding smaller }
Comments
Post a Comment