Advertisement
Guest User

java void mergesort takes only arrays as args

a guest
Jul 23rd, 2017
101
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 7.94 KB | None | 0 0
  1. package main;
  2. import java.util.Random;
  3. /**
  4.  * Implements various sorting algorithms.
  5.  *
  6.  * @author --zaux
  7.  * @verison 1.0
  8.  */
  9.  
  10. public class BaseSorting {
  11.      
  12.     /**
  13.      * Entry point for sample output.
  14.      *
  15.      * @param args the command line arguments
  16.      */
  17.     public static void main(String[] args) {
  18.       Random rand = new Random();
  19.         //Q1
  20.         String[] a = {"S", "O", "R", "T", "E", "X", "A", "M", "P", "L", "E"};
  21.         show(a);
  22.         quicksortmid(a);
  23.         assert isSorted(a); //requires assertions enabled.
  24.         show(a);
  25.        
  26.         //Q2
  27.         String[] b = {"S", "O", "R", "T", "E", "X", "A", "M", "P", "L", "E"};
  28.         mergeSort(b);
  29.         assert isSorted(b);
  30.         show(b);
  31.        
  32.         // Produces erroneous sorting on incorrect algorithms;
  33.         Integer[] c = {7, 3, 2, 4, 9, 10, 1,2, 22, 23, 0, 1, 10};
  34.         show(c);
  35.         quicksortmid(c);
  36.         show(c);
  37.        
  38.         /*
  39.         // Output is not formatted
  40.         Integer[] d = new Integer[1000];
  41.         int shrink = 1000;
  42.         for(int x = 0; x < 1000; x++){
  43.           //Uncomment to test with random numbers
  44.           //d[x] = rand.nextInt(1000);
  45.           d[x] = shrink;
  46.           shrink--;
  47.         }
  48.         show(d);
  49.         quicksortmid(d);
  50.         show(d);
  51.         */
  52.         System.out.println("\n\n");
  53.         Integer[] e = {7, 3, 2, 4, 9, 10, 1, 2, 22, 23, 0, 1, 10};
  54.         show(e);
  55.         mergeSort(e);
  56.         show(e);
  57.        
  58.         Integer[] x = new Integer[100000];
  59.         for(int xx = 0; xx < x.length; xx++)
  60.           x[xx] = rand.nextInt(100);
  61.         show(x);
  62.         mergesort(x);
  63.         show(x);
  64.        
  65.        
  66.  
  67.     }
  68.    
  69.     public static void quicksortmid(Comparable[] a) {
  70.         quicksortmid(a, 0, a.length-1);
  71.     }
  72.    
  73.     private static void quicksortmid(Comparable[] data, int min, int max){
  74.       if(min < max){
  75.         // create partitions
  76.         int indexofpartition = partition(data, min, max);
  77.         //sor the left partition (lower values)
  78.         quicksortmid(data, min, indexofpartition-1);
  79.         //sort the right partition (higher values)
  80.         quicksortmid(data, indexofpartition+1, max);
  81.       }
  82.     }
  83.    
  84.     private static <T extends Comparable<T>>int partition(T[] data, int min, int max){
  85.       T partitionelement, small, med, large;
  86.       int left,right;
  87.       int middle = (min+max)/2;
  88.       small = data[min];
  89.       large = data[max];
  90.       med = data[middle];
  91.      
  92.       int partitionIndex = min;
  93.       partitionelement = small;
  94.      
  95.       // compare the elements of the 3 indexes selected and select the partitionelement
  96.       if (small.compareTo(med) > 0 && small.compareTo(large) < 0){
  97.         partitionelement = small;
  98.         partitionIndex = min;
  99.       }
  100.       else if(med.compareTo(small) > 0 && med.compareTo(large) < 0){
  101.         partitionelement = med;
  102.         partitionIndex = middle;
  103.       }
  104.       else if(large.compareTo(small) > 0 && small.compareTo(med) < 0){
  105.         partitionelement = large;
  106.         partitionIndex = max;
  107.       }
  108.       // JMO: fixed the swap, was swapping with middle, when i should have been swapping with
  109.       //      partition index.
  110.       swap(data,partitionIndex, min);
  111.      
  112.       left = min;
  113.       right = max;
  114.        
  115.       while (left < right){
  116.         // search for an element that is > the partition element
  117.         while (left < right && data[left].compareTo(partitionelement) <= 0)
  118.           left++;
  119.            
  120.         // search for an element that is < the partition element
  121.         while (data[right].compareTo(partitionelement) > 0)
  122.           right--;
  123.            
  124.         // swap the elements
  125.         if (left < right)
  126.           swap(data, left, right);
  127.       }
  128.        
  129.         // move the partition element into place
  130.       swap(data, min, right);
  131.        
  132.       return right;
  133.      
  134.     }
  135.     /**
  136.      * Swaps two values at two given indexes, helps partition, which helps quicksort
  137.      * @param data
  138.      * @param index1
  139.      * @param index2
  140.      */
  141.     public static void swap(Comparable[] data, int index1, int index2){
  142.       Comparable tmp = data[index1];
  143.       data[index1] = data[index2];
  144.       data[index2] = tmp;
  145.     }
  146.    
  147.    
  148.     public static void mergesort(Comparable[] a) {
  149.       mergeSort(a);
  150.     }
  151.    
  152.     /**
  153.      * Helper method for mergesort, returns sorted array through recursion;
  154.      * @param a the array to be sorted
  155.      * @return a sorted array
  156.      */
  157.     public static Comparable[] mergeSort(Comparable[] a){
  158.      
  159.       // Since this method will be recursive we set up some logic for the
  160.       // base case since arrays of size 1 are already sorted by default
  161.       // we only act on arrays of length > 1
  162.       if(a.length > 1){
  163.         int mid = (a.length)/2;
  164.         int rest = a.length-mid;
  165.         //initially set to size [max-mid]
  166.         Comparable[] split1 = new Comparable[mid];
  167.         Comparable[] split2 = new Comparable[rest];
  168.        
  169.         // Copy the items from a into the 2 sub arrays
  170.         for(int x = 0; x < mid; x++){
  171.           split1[x] = a[x];
  172.         }
  173.         for(int x = 0 ; x < rest ; x++){
  174.           split2[x] = a[x+mid];
  175.         }
  176.        
  177.         //Recursive call on the two subarrays
  178.         mergeSort(split1);
  179.         mergeSort(split2);
  180.        
  181.         // merge the two subarrays and store those values in a
  182.         for(int x = 0; x < a.length; x++){
  183.           a[x] = merge(split1,split2)[x];
  184.         }
  185.      }
  186.      return a;
  187.     }
  188.     /**
  189.      * Takes two sorted arrays and merges them by with the lowest value first;
  190.      * @param a the sub array to merge into the merged array
  191.      * @param b the sub array to merge into the merged array
  192.      * @return a merged, sorted array.
  193.      */
  194.     public static Comparable[] merge(Comparable[] a, Comparable[] b){
  195.       //Initial runs threw AIOB exception, the issue was that below we subtracted 1
  196.       // from a.length and b.length which is incorrect as it should just be the length of both
  197.       Comparable[] merged = new Comparable[(a.length)+(b.length)];
  198.       int alast = a.length-1;
  199.       int blast = b.length-1;
  200.       int  afirst = 0, bfirst = 0, mindex = 0;
  201.      
  202.       while((afirst <= alast) && (bfirst <= blast)){
  203.         //
  204.         if(a[afirst].compareTo(b[bfirst]) > 0){
  205.          merged[mindex] = b[bfirst];
  206.          mindex++;
  207.          bfirst++;
  208.         } else if (a[afirst].compareTo(b[bfirst]) < 0){
  209.            merged[mindex] = a[afirst];
  210.            mindex++;
  211.            afirst++;
  212.         } else{
  213.          //Else the two compared values are equal
  214.          merged[mindex] = b[bfirst];
  215.          merged[mindex+1] = a[afirst];
  216.          //both a/b indexes get incremented
  217.          afirst++;
  218.          bfirst++;
  219.          // merge index gets incremented by 2 because we stored two values
  220.          // on the pass
  221.          mindex += 2;
  222.         }
  223.       }
  224.       //copy remaining elements
  225.       while(afirst <= alast){
  226.         merged[mindex] = a[afirst];
  227.         afirst++;
  228.         mindex++;
  229.       }
  230.       while(bfirst <= blast){
  231.         merged[mindex] = b[bfirst];
  232.         bfirst++;
  233.         mindex++;
  234.       }
  235.      
  236.      return merged;
  237.     }
  238.     /**
  239.      * Displays contents of array, space separated.
  240.      * @author Sedgewick
  241.      * @param a Array to display.
  242.      */
  243.     private static void show(Comparable[] a) {
  244.         for (Comparable a1 : a)
  245.             System.out.print(a1 + " ");
  246.  
  247.         System.out.println();
  248.     }
  249.    
  250.     /**
  251.      * Checks if array is in sorted order.
  252.      * @author Sedgewick
  253.      * @param a Array to be checked.
  254.      * @return Returns true if array is sorted.
  255.      */
  256.     public static boolean isSorted(Comparable[] a) {
  257.         for (int i = 1; i < a.length; i++)
  258.             if (less(a[i], a[i-1]))
  259.                 return false;
  260.        
  261.         return true;
  262.     }
  263.    
  264.     //See previous method.
  265.     private static boolean less(Comparable v, Comparable w) {
  266.         return v.compareTo(w) < 0;
  267.     }
  268. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement