Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- private static void quickSort(int[] array, int lowIndex, int highIndex) //A quicksort for only a specified range of a given array - recursable
- {
- //First of all - stopping conditions
- if (lowIndex + 1 >= highIndex) //If there are two members
- {
- if (array[lowIndex] > array[highIndex]) //If they aren't sorted
- swap(array,lowIndex,highIndex); //Swap them
- return; //A presto, we're sorted on this levl
- }
- //Else - meaning more than 2 members
- //First, we need to partition the array in it's bounds.
- int mIndex = partition (array, lowIndex, highIndex); //This partitions the array into members smaller and bigger than the pivot (which is found in-method). It then gets the index of the median.
- //Now we have to recurse this on each of the sub-arrays (partitions)
- quickSort(array, lowIndex, mIndex - 1); //Quicksorts the subarray between the lowest index given and the median.
- quickSort(array, mIndex + 1, highIndex); //Quicksorts the subarray between the median and the highest index.
- }
- private static int partition(int[] array, int lowIndex, int highIndex) //This partitions the array into members smaller and bigger than the pivot.
- {
- int midIndex = ((lowIndex + highIndex) / 2); //sets the middle index
- int pivot = findMedian(array, lowIndex + 1, highIndex, midIndex); //Finds the index of the approximate median member and uses it as pivot
- swap(array, lowIndex, pivot); //Swaps the first element of the given bounds with the pivot
- int medianIndex = partition (array, lowIndex + 1, highIndex);
- swap(array, lowIndex, pivot);
- return pivot;
- }
- private static int findMedian(int[] array, int lowIndex, int highIndex, int midIndex)
- {
- //This method compares three members of the array and returns the index of the median amongst them (value-wise).
- if (array[lowIndex] <= array[highIndex]) // L <= H (low < high)
- if (array[highIndex] <= array[midIndex]) // L <= H <= M == H
- return highIndex;
- else if (array[lowIndex] <= array[midIndex]) // L <= M <= H == M
- return midIndex;
- else // M <= L <= H == L - only remaining option
- return lowIndex;
- else //L > H
- if (array[lowIndex] <= array[midIndex]) // H < L <= M == L
- return lowIndex;
- else if (array[highIndex] <= array[midIndex]) //H <= M < L
- return midIndex;
- else // M <= H < L == M, only remaining option
- return highIndex;
- }
- private static void swap(int[] array, int n, int m)
- {
- //This swaps two members of a given array
- int tmp = array[n];
- array[n] = array[m];
- array[m] = tmp;
- }
Add Comment
Please, Sign In to add comment