Advertisement
Guest User

Untitled

a guest
Sep 15th, 2019
106
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.83 KB | None | 0 0
  1. package split_sort_merge;
  2.  
  3. import java.util.Arrays;
  4.  
  5. /**
  6.  * We use this class to perform the the sorting in assignment 1.4
  7.  * Base case as long as the array is longer than the threshold,
  8.  * we slice the array in smaller partitions and make new threads
  9.  */
  10. public class RecursiveSort implements Runnable {
  11.  
  12.     private int[] intArray;
  13.     private int threshold;
  14.  
  15.  
  16.     public RecursiveSort(int[] intArray, int threshold) {
  17.         this.intArray = intArray;
  18.         this.threshold = threshold;
  19.     }
  20.  
  21.     @Override
  22.     public void run() {
  23.         BubbleSort bubbleSort = new BubbleSort();
  24.         if (intArray.length < threshold) {
  25.             bubbleSort.bubbleSort(intArray);
  26.         } else {
  27.             ArraySplitter arraySplitter = new ArraySplitter();
  28.             arraySplitter.split(intArray); // splits the arrays in half as long as the recursive state persists
  29.  
  30.             int[] a = arraySplitter.getA();
  31.             int[] b = arraySplitter.getB();
  32.  
  33.             // instantiates thread 1 and 2 or a new thread when in recursive state
  34.             Thread t1 = new Thread(new BubbleSort(a)); // instantiates new thread as long as recursive state persists
  35.             Thread t2 = new Thread(new BubbleSort(b));
  36.  
  37.             // starts thread 1 or a new thread when in recursive state
  38.             t1.start(); // starts threads as long as recursive state persists
  39.             t2.start();
  40.  
  41.             try {
  42.                 t1.join();
  43.                 t2.join();
  44.             } catch (InterruptedException e) {
  45.                 e.printStackTrace();
  46.             }
  47.  
  48.             Merge merge = new Merge();
  49.             int[] result = merge.mergeArrays(a, b); // we merge partition a and b back into one sorted array
  50.  
  51.             System.out.println("Sorted array is:\n"
  52.                     + Arrays.toString(result));
  53.         }
  54.     }
  55. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement