/* * Lab 14, Task 4 * * Challenge Task */ public class Lab14Task4 { /** insertionSort */ public static void insertionSort(int[] arr) { for (int i = 1; i < arr.length; i++) { if (arr[i] < arr[i-1]) { // Save a copy of the element to be inserted. int toInsert = arr[i]; // Shift right to make room for element. int j = i; do { arr[j] = arr[j - 1]; j = j - 1; } while (j > 0 && toInsert < arr[j-1]); // Put the element in place. arr[j] = toInsert; } } } /* swap - helper method for partition */ public static void swap(int[] arr, int a, int b) { int temp = arr[a]; arr[a] = arr[b]; arr[b] = temp; } /* partition - helper method for qSort */ public static int partition(int[] arr, int first, int last) { int pivot = arr[(first + last)/2]; int i = first - 1; // index going left to right int j = last + 1; // index going right to left while (true) { // moving from left to right, find an element >= the pivot do { i++; } while (arr[i] < pivot); // moving from right to left, find an element <= the pivot do { j--; } while (arr[j] > pivot); // If the indices still haven't met or crossed, // swap the elements so that they end up in the correct subarray. // Otherwise, the partition is complete and we return j. if (i < j) { swap(arr, i, j); } else { return j; // index of last element in the left subarray } } } /* qSort - recursive method that does the work for quickSort */ private static void qSort(int[] arr, int first, int last) { int split = partition(arr, first, last); if (first < split) { qSort(arr, first, split); // left subarray } if (last > split + 1) { qSort(arr, split + 1, last); // right subarray } } /** quicksort */ public static void quickSort(int[] arr) { qSort(arr, 0, arr.length - 1); } }