Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
public class QuickSortTest {
public static final int max = 10;
public static void main(String[] args){
int[] toSortArray = new int[max];
for(int i = 0; i < max; i++){
toSortArray[i] = (int) (Math.random()*100);
}
System.out.println("The array to be sorted is:");
for(int i = 0; i < max; i++){
System.out.print(" | " + toSortArray[i]);
}
System.out.println(" | ");
//Beginning of the algorithm
quicksortHelper(toSortArray, 0 , max-1);
// End of the algorithm
System.out.println("The sorted array is: ");
for(int i = 0; i < max; i++){
System.out.print(" | " + toSortArray[i]);
}
System.out.println(" | ");
}
private static void quicksortHelper(int[] toSortArray, int first, int last) {
if(first < last){
int splitpoint = partition(toSortArray, first, last);
quicksortHelper(toSortArray, first, splitpoint-1);
quicksortHelper(toSortArray, splitpoint+1, last);
}
}
private static int partition(int[] toSortArray, int first, int last) {
int pivot = toSortArray[first];
int leftmark = first+1;
int rightmark = last;
boolean done = true;
while(done){
while(leftmark<=rightmark && toSortArray[leftmark] < pivot){
leftmark++;
}
while(leftmark<=rightmark && toSortArray[rightmark] > pivot){
rightmark--;
}
if(leftmark>rightmark){
done = false;
}else{
int temp = toSortArray[leftmark];
toSortArray[leftmark] = toSortArray[rightmark];
toSortArray[rightmark] = temp;
}
}
int temp = toSortArray[rightmark];
toSortArray[rightmark] = toSortArray[first];
toSortArray[first] = temp;
return rightmark;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.