Question
In java, check if the quicksort algorithm is correctly implemented. If not, edit the code to fix it. public class KthSmallest { private static void
In java, check if the quicksort algorithm is correctly implemented. If not, edit the code to fix it.
public class KthSmallest {
private static void swap(int[] theArray, int i, int j){
int temp = theArray[i];
theArray[i] = theArray[j];
theArray[j] = temp;
}
private static int partition(int[] theArray, int first, int last){
// Returns the index of the pivot element after partitioning
// theArray[first..last]
int p = theArray[first]; // use the first item of the array as the pivot (p)
int lastS1 = first; // set S1 and S2 to empty
// ToDo: Determine the regions S1 and S2
// Refer to the quicksort algorithm
while (first <= last) {
//searching number which is greater than pivot, bottom up
while(theArray[first]< p) {
first++;
}
//searching number which is less than pivot, top down
while (theArray[last] > p) {
last--;
}
//swap the values
if (first <= last) {
int tmp = theArray[first];
theArray[first] = theArray[last];
theArray[last] = tmp;
//increment first index and decrement last index
first++;
last--;
}
}
return lastS1; // the index of the pivot element
}
Step by Step Solution
There are 3 Steps involved in it
Step: 1
Get Instant Access to Expert-Tailored Solutions
See step-by-step solutions with expert insights and AI powered tools for academic success
Step: 2
Step: 3
Ace Your Homework with AI
Get the answers you need in no time with our AI-driven, step-by-step assistance
Get Started