package project;
public class QuickSort {
Comparable theArray[];
public void sort(Comparable theArray[]) {
this.theArray = theArray;
sort_recursive(0, theArray.length - 1);
}
private void sort_recursive(int partition_start, int partition_end) {
if (partition_start == partition_end) {
return; //base case , it the sub array length is zero, then sorted
}
int pivotLocation = partition(partition_start, partition_end); //use the partition algorythm to find pivot location
if (pivotLocation != partition_start) { //if the pivot is not the smallest value
sort_recursive(partition_start, pivotLocation - 1); //then quick sort the values before the partition
}
if (pivotLocation != partition_end) { //if the pivot is not the largest value
sort_recursive(pivotLocation + 1, partition_end); //then quick sort the values after the partition
}
}
//partition algorythm
private int partition(int bottom, int top) {
int down = bottom;
int up = top;
Comparable pivot = theArray[bottom];
while (true) {
while (!(theArray[down].compareTo(pivot) > 0)) {
down++; // increase down pointer untill a value greater than pivot value is found
if (down == top) {
break; //the boundry conditions of the partition
}
}
while (!(theArray[up].compareTo(pivot) <= 0)) {
up--; // decrease up pointer untill a value less than or equal to pivot value is found
if (up == bottom) {
break;//the boundry conditions of the partition
}
}
if (up > down) {
Swapper.swap(theArray, up, down); //if up is greater than down then swap the up position value and down position value
} else {
Swapper.swap(theArray, up, bottom); //else then swap the up position value and pivot position value, here the pivot is selected as the first element in the sub array
return up; //pivot location is found, which is the up position
}
}
}
}
package project;
//Swaps the values of two locations in a specific Array
public class Swapper {
public static void swap(Comparable[] theArray, int position1, int position2) {
Comparable temp = theArray[position1];
theArray[position1] = theArray[position2];
theArray[position2] = temp;
}
}