Created
March 3, 2019 03:30
-
-
Save graphoarty/d01f9bf32967232b858377a07a3ee6a3 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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