Advertisement
Guest User

Sorting Algorithms

a guest
Mar 21st, 2018
85
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 7.57 KB | None | 0 0
  1. public class Algorithms {
  2.     /**
  3.      * nlogn - Quicksort
  4.      * n^2 - Insertion Sort
  5.      */
  6.     public static void main(String[] args) {
  7.         int[] quickData = {10, 9, 1, 18, 5, 6, 2, 12, 15, 7};
  8.         int[] insertionData = {10, 9, 1, 18, 5, 6, 2, 12, 15, 7};
  9.  
  10.         // QUICK-SORT
  11.         printArray(quickData);
  12.         checkArrayForIntegrity(quickData, "Pre - QuickSort");
  13.         QuickSort quickSortObject = new QuickSort();
  14.         // Begin the sort with the smallest at element 0, largest at array.length and move inwards recursively
  15.         quickSortObject.sort(quickData, 0, quickData.length - 1);
  16.         printArray(quickData);
  17.         checkArrayForIntegrity(quickData, "Post - QuickSort");
  18.  
  19.  
  20.         // INSERTION SORT
  21.         printArray(insertionData);
  22.         checkArrayForIntegrity(insertionData, "Pre - InsertionSort");
  23.  
  24.         InsertionSort insertionSortArray = new InsertionSort();
  25.         int[] postInsertionSortData = insertionSortArray.sort(insertionData);
  26.  
  27.         printArray(postInsertionSortData);
  28.         checkArrayForIntegrity(postInsertionSortData, "Post - InsertionSort");
  29.  
  30.     }
  31.  
  32.  
  33.     private static double getTotalRuntime(double startingRunTime) {
  34.         return System.currentTimeMillis() - startingRunTime;
  35.     }
  36.  
  37.     private static void printArray(int[] inputArray) {
  38.         System.out.print("\nArray Status: ");
  39.         for (int currentArrayFocus : inputArray) {
  40.             System.out.print(currentArrayFocus + " ");
  41.         }
  42.         System.out.print("\n");
  43.     }
  44.  
  45.     // Returns a check on whether or not the new array has been properly sorted from greatest to least
  46.     private static void checkArrayForIntegrity(int[] array, String consoleStringMessage) {
  47.         boolean status = true;
  48.         for (int i = 0; i < array.length && status; i++) {
  49.             // As soon as there's a falsity this essentially breaks the loop and forces it to return false
  50.             if (i < (array.length - 1)) {
  51.                 // ^^^^ Make sure it iterates up till the last element to prevent an OutOfBoundsException
  52.                 // Resulting in it stopping at the 2nd-last element
  53.                 status = array[i] < array[i + 1];
  54.             }
  55.         }
  56.         System.out.println("Integrity : [" + consoleStringMessage + "] : [" + status + "]\n");
  57.     }
  58. }
  59.  
  60.  
  61. class InsertionSort extends Algorithms {
  62.  
  63.     // This didn't work :(
  64.  
  65.     /*
  66.     private int[] inputArray = {};
  67.  
  68.     int[] sort(int[] inputArray) {
  69.  
  70.         int j, currentNumber;
  71.         // Start the sort at the 2nd element and compare backwards, could start at zero and compare forwards but I
  72.         // rather wouldn't because of it being easier to ArrayOutOfBoundsException
  73.         for (int i = 1; i < inputArray.length; i++) {
  74.             currentNumber = inputArray[i];
  75.             j = i;
  76.  
  77.             // Check so that the i-1 focus we have is in the array limitations, and that it's greater than the number,
  78.             // then if so then move it over in position
  79.             while (j > 0 && inputArray[j] > currentNumber) {
  80.                 inputArray[i] = inputArray[j - 1];
  81.                 j--;
  82.             }
  83.             inputArray[j] = currentNumber;
  84.         }
  85.  
  86.         // Store the array to reference later cause apparently is doesn't want to behave :(
  87.         this.inputArray = inputArray;
  88.         return this.inputArray;
  89.     }
  90.     */
  91.  
  92.     // But this did :)
  93.     public int[] sort (int[] inputArray) {
  94.         int pivot;   // Self Explanatory
  95.         int backwardsComparisonKey;
  96.         // ^^^^ When we make the comparison, use this to iterate back in the array as many times as necessary until fine
  97.         int currentNumberKey; // What number we're looking at initially on the pivot
  98.         int tempSwapNumber; // Self explanatory as well, but the space we use to swap the numbers each time we iterate
  99.  
  100.         // Set the pivot at 1 so we can look back. Could also do it at the start and compare forwards but this works
  101.         for (pivot = 1; pivot < inputArray.length; pivot++) {
  102.             currentNumberKey = inputArray[pivot];
  103.             // Sets up a simple way to reference the number before the 'focus' of the loop
  104.             backwardsComparisonKey = pivot - 1;
  105.  
  106.             // Wouldn't want the comparison we're making to go into the negative portions of the array would we? ;)
  107.             // Also, guarantee that it will only swap the pivot and the number before it if it's actually less than it
  108.             while (backwardsComparisonKey >= 0 && currentNumberKey < inputArray[backwardsComparisonKey]) {
  109.                 tempSwapNumber = inputArray[backwardsComparisonKey];
  110.                 inputArray[backwardsComparisonKey] = inputArray[backwardsComparisonKey + 1];
  111.                 inputArray[backwardsComparisonKey + 1] = tempSwapNumber;
  112.  
  113.                 // Iterate the key backwards and see if the number before the backwardsComparisonKey can also be swapped
  114.                 //  out or not.
  115.                 backwardsComparisonKey--;
  116.             }
  117.         }
  118.         // Tried to do this with a void method like in quicksort, but it didn't seem to like that and treated it as
  119.         // though it was static. Not sure why, but this works also, so why not.
  120.         return inputArray;
  121.     }
  122.  
  123. }
  124.  
  125. class QuickSort extends Algorithms {
  126.     /**
  127.      * Requires two portions to the algorithm, one partitions and one sorts.
  128.      * In this case I decided to set the pivot at the end of the array, as per the first line of the partition()
  129.      * method.
  130.      */
  131.     private int partition(int[] inputArray, int lowestIndex, int highestIndex) {
  132.  
  133.         int pivotPoint = inputArray[highestIndex]; // Use the last element in the [current] array to be the pivot
  134.         int i = (lowestIndex - 1);
  135.  
  136.         for (int j = lowestIndex; j < highestIndex; j++) {
  137.             /**
  138.              ^^ Goes from the lowestIndex to highestIndex and iterates through (of the sample size we're
  139.              recursively looking at right now)
  140.              If the current element is smaller or equal to the pivot - go ahead and swap
  141.              */
  142.             if (inputArray[j] <= pivotPoint) {
  143.                 i++; // Moves where we need to consider the elements because an element has to go behind.
  144.                 // Needs to swap the index of the j
  145.                 int temp = inputArray[i];
  146.                 inputArray[i] = inputArray[j];
  147.                 inputArray[j] = temp;
  148.             }
  149.         }
  150.  
  151.         // Swap the smaller element and the highest targeted element (which may be the pivot) around
  152.  
  153.         int temp = inputArray[i + 1];
  154.         inputArray[i + 1] = inputArray[highestIndex];
  155.         inputArray[highestIndex] = temp;
  156.  
  157.         // Returns one above the 'pivot'
  158.         return i + 1;
  159.     }
  160.  
  161.     void sort(int[] inputArray, int lowestIndex, int highestIndex) {
  162.         // Only run if the low is actually the lowestIndex - Base case for recursion so it doesn't stack overflow
  163.         if (lowestIndex < highestIndex) {
  164. //            System.out.println("Entering Sort Method, lowest index " + lowestIndex + "[:" + inputArray[lowestIndex]
  165. //                    + "] and highest index " + highestIndex + "[:" + inputArray[highestIndex] + "]");
  166.  
  167.             int partitionIndex = partition(inputArray, lowestIndex, highestIndex);
  168.             // This is where we actually recursively sort stuff above and below the pivot point
  169. //            System.out.println("Starting Recursive Spawning");
  170.  
  171.             sort(inputArray, lowestIndex, partitionIndex - 1); // Covers first half
  172.             sort(inputArray, partitionIndex + 1, highestIndex); // Covers second half
  173.         }
  174.     }
  175.  
  176. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement