My brother wants me to optimize my code by only having one loop. I don't see how a Quicksort can only have one loop and work. (He told me to remove the inner loop)
public class QuickSort {
public static void Quick(int[] target, int lo, int hi) {
if (lo >= hi) {
return;
}
Random numberGenerator = new Random();
int pivot = numberGenerator.nextInt(hi-lo)+lo;
int pivotValue = target[pivot];
target[pivot]=target[hi];
target[hi]=pivotValue;
pivot=hi;
int counter;
for(counter=lo; counter<pivot ; counter++){
while(target[counter]>target[pivot]){
if(pivot-counter==1){
int temp=target[counter];
target[counter]=target[pivot];
target[pivot]=temp;
//return; //possibly the problem
}
else{
int temp1 = target[pivot-1];
int temp2 = target[pivot];
target[pivot]=target[counter];
target[pivot-1]=temp2;
target[counter]=temp1;
pivot=pivot-1;
}
}
}
Quick(target, lo, counter-1);
Quick(target, counter, hi);
}
public static void main(String[] args) {
int sizeOfArray = 10;
int numberOfTests = 1000;
int numFailed = 0;
for (int i = 0; i < numberOfTests; i++)
{
int[] iNeedSorting = new int[sizeOfArray];
populateArrayWithRandomNums(iNeedSorting);
//System.out.printf("Test #%d\n", i);
//System.out.printf("Original Array: %s\n", intArrayToString(iNeedSorting));
Quick(iNeedSorting, 0, iNeedSorting.length-1);
if (!isSorted(iNeedSorting)) {numFailed++;}
//System.out.printf("New Array: %s\n\n", intArrayToString(iNeedSorting));
}
System.out.printf("%d test failed\n\n", numFailed);
}
}