Util Merge Sort by 9bXN09

VIEWS: 7 PAGES: 2

									                                  Class UtilMergeSort — MergeSort Based on List Behaviors
/**                                                                          // One side has gone empty.   Move across the other
 * Explicit implementation of merge sort on top of the class                 if (left.isEmpty())
 * java.util.LinkedList --- compared with Collections.sort and                  list.addAll(right);
 * also our explicit linked list implementation.                             else
 *                                                                              list.addAll(left);
 * @author Timothy Rolfe                                                 }
 *
 * Specimen execution on cscd-201-07-l.eastern.ewu.edu                   // Explicit implementation of linked list merge sort using
Size of the list: 50000                                                  // just the bare header node and size.
Elapsed: 783.859 milliseconds, 718194 comparisons --- our code           static Node myMergeSort(Node head, int size)
Elapsed: 482.371 milliseconds, 735921 comparisons --- Collections.sort   { int sizeL = size/2,
Elapsed: 137.625 milliseconds, 718194 comparisons --- our linked list            sizeR = size - sizeL,
version                                                                          k;
 *                                                                          Node listL = head,
 * NOTE: this requires the class MyComparable.java                               listR,
 */                                                                              tail = new Node(null); // as dummy header
import java.util.*;
                                                                             if (size < 2) return head;
public class UtilMergeSort                                                   // Traverse to the end of the left sublist
{                                                                            for (k = 1; k < sizeL; k++) // note start at 1, not 0
   /**                                                                          listL = listL.next;
    * Merge sort logic built on top of java.util.LinkedList based upon       listR = listL.next;         // start of the right sublist
    * existing behaviors actually from the List interface:                   listL.next = null;          // terminate the left sublist
    * clear, peek, add, remove, and addAll.                                  listL = head;               // and regenerate the header.
    *                                                                        listL = myMergeSort(listL, sizeL);
    * @param list The linked list to be sorted                               listR = myMergeSort(listR, sizeR);
    */                                                                       head = tail; // Dummy header
   static void mergeSort(LinkedList<Comparable> list)                        // While both list have contents
   { // Use two sublists.                                                    while (listL != null && listR != null)
      LinkedList<Comparable> left, right;                                    { if (listL.item.compareTo(listR.item) <= 0)
      int size = list.size(),                                                   { tail.next = listL; listL = listL.next; }
          sizeL = size/2;         // floor(size/2)                              else
      // sizeR = size - size/2; // ceil(size/2)                                 { tail.next = listR; listR = listR.next; }
                                                                                tail = tail.next;
      if (size < 2) return;                                                  }
      // Generate the two sublists                                           // Append the non-empty list
      left = new LinkedList<Comparable>();                                   if (listL != null)
      right = (LinkedList<Comparable>) list.clone();                            tail.next = listL;
      list.clear();               // Will be regenerated in place            else
                                                                                tail.next = listR;
      // Move the front of the list into the left sublist                    return head.next; // Discard dummy header
      while (sizeL-- > 0)                                                }
         left.add(right.remove());
                                                                         // Not a full linked list implementation, but explicit
      // Recursively sort the sublists                                   // manipulation of a linked list node.
      mergeSort(left); mergeSort(right);                                 private static class Node implements Comparable
                                                                         { Comparable item;
      // While both lists have contents, move data items to list            Node       next;
      while ( !( left.isEmpty() || right.isEmpty() ) )
         if (left.peek().compareTo(right.peek()) <= 0)                       Node(Comparable item)
            list.add(left.remove());                                         { this(item, null); }
         else                                                                Node (Comparable item, Node next)
            list.add(right.remove());                                        { this.item = item; this.next = next;    }



Printed 2012-Aug-31 at 07:43
       public int compareTo(Object o)                                              for ( k = 0; k < size; k++ )
       { return item.compareTo(((Node)o).item);    }                                  list.addFirst ( new MyComparable
                                                                                                    ( new Integer(gen.nextInt(900) + 100)));
       // For debugging purposes: the list from here on.                           start = System.nanoTime();
       public String toString()                                                    Collections.sort(list);
       { StringBuilder rtn = new StringBuilder("[");                               System.out.printf ("Elapsed: %3.3f milliseconds, %d comparisons",
          Node current = this;                                                        (System.nanoTime() - start)*1E-6, MyComparable.nCompares());
                                                                                   if (size < 50)
           if (current != null)                                                       System.out.println(" --- Collections.sort\n" + list);
           { rtn.append(current.item);                                             else
              current = current.next;                                                 System.out.println(" --- Collections.sort");
              while (current != null)
              { rtn.append(", " + current.item);                                   gen.setSeed(seed);
                 current = current.next;                                           for ( k = 0; k < size; k++ )
              }                                                                       head = new Node ( new MyComparable
           }                                                                                          ( new Integer(gen.nextInt(900) + 100)),
           rtn.append("]");                                                                             head);
           return rtn.toString();                                                  start = System.nanoTime();
       }                                                                           head = myMergeSort(head, size);
   }                                                                               System.out.printf ("Elapsed: %3.3f milliseconds, %d comparisons",
                                                                                      (System.nanoTime() - start)*1E-6, MyComparable.nCompares());
   public static void main ( String[] args )                                       if (size < 50)
   { Scanner console = new Scanner(System.in);                                        System.out.println(" --- our linked list version\n" + head);
      int     index, size, k;                                                      else
      LinkedList list = new LinkedList();                                             System.out.println(" --- our linked list version");
      Node head = null;
      java.util.Random gen = new java.util.Random();                               System.out.print("Press <ENTER> to exit: ");   console.nextLine();
      long start,                                                              }
           seed = gen.nextLong(); // Two identical sequences               }

       System.out.print ("Size of the list: ");
       if ( args.length > 0 )
       { size = Integer.parseInt(args[0]);
          System.out.println(size);
       }
       else
       { size = console.nextInt(); console.nextLine(); }
       if (args.length > 1 )
          seed = Long.parseLong(args[1]);
       // Generate the LinkedList object.
       gen.setSeed(seed);
       for ( k = 0; k < size; k++ )
          list.addFirst ( new MyComparable
                        ( new Integer(gen.nextInt(900) + 100)));
       if (size < 50)
          System.out.println("Before sort:\n" + list);
       start = System.nanoTime();
       mergeSort(list);
       System.out.printf ("Elapsed: %3.3f milliseconds, %d comparisons",
          (System.nanoTime() - start)*1E-6, MyComparable.nCompares());
       if (size < 50)
          System.out.println(" --- our code\n" + list);
       else
          System.out.println(" --- our code");
       // Regenerate the list
       list.clear();
       gen.setSeed(seed);

Printed 2012-Aug-31 at 07:43

								
To top