Thread: Merge Sort Help
View Single Post
  #5 (permalink)  
Old 01-30-2008, 04:17 AM
Hollywood Hollywood is offline
Member
 
Join Date: Jan 2008
Posts: 5
Hollywood is on a distinguished road
Hardwired, I just need to find a way to use your merge in my merge.

Ok I am sorry I forgot to implement an order I am not using Comparable.
Here is my new code. I have some of the merge algorithm but am a little stuck.
I have tested the split method and it is splitting fine it is when I merge, and I have more than two elements of each half when some aren't fully comparing w/ the others.

I am inputing this list of Integers "8,4,1,6,4,3,2,6"
my output so far looks like this "1,2,3,6,6,4,4,8"
4 is not after 6
Code:
package sort; import utilities.containers.*; /** * This class subdivides a list of elements into a subsequences of elements, * then merges the single elements in order to form a single ordered list. */ public class ListUtilities { /** * MergeSort Starting algorithm. * Require: a non-empty list of elements to sort. * Ensure: returns the input list in increasing order. */ public static <E> List <E> mergesort(Order<E> order,List <E> toSort){ List<E> result = toSort.copy(); if (toSort.size()<=1){ /*Do Nothing*/ } else{ int low = 0; int high = result.size()-1; split(order,result,low,high); } return result; } /** * Private split method used to break down input list into single list elements. * */ private static <E> void split(Order<E> order,List <E> toSort,int low,int high){ if(low==high){ /*Do Nothing*/ //return split; } else{ int middle = (high+low)/2; split(order,toSort,low,middle); split(order,toSort,middle+1,high); merge(order,toSort,low, middle, high); } } /** * Private merge method used to merge and order two generic lists. * As elements are merged they are sorted according to order. */ private static <E> void merge(Order<E> order,List<E> toSort,int low, int middle, int high){ int i = middle; int j = middle+1; while((low<=i)&&(j<=high)){ if(order.inOrder(toSort.get(low),toSort.get(j))){ low++; } else{ swap(toSort,low,j); j++; } } } /** * Swaps two generic elements of a list. */ private static <E> void swap(List<E> toSort,int left, int right){ E temp = toSort.get(left); toSort.set(left,toSort.get(right)); toSort.set(right,temp); } }//end of class MergeSort

Last edited by Hollywood : 01-30-2008 at 07:23 AM.
Reply With Quote