-
Quick sort problem
the professor wrote a quick sort algorithm on the board and just told us to copy and read it at home. How ever it didn't run and i tried my best to learn it online and fix the code but it still doesn't seem to run, or im misunderstanding quick sort.
Code:
public class QuickSort{
public QuickSort(int[] anArray){
a=anArray;
}
public void sort(int from,int to){
if(from>=to) return;
int p=partition(from,to);
sort(from,to);
sort(p+1,to);
}
private int partition(int from,int to){
int pivot=a[from];
int j=to+1;
int i=from;
while(i<j){
i++;
while(a[i]<pivot)i++;
j--;
while(a[j]>pivot)j--;
if(i<j)
swap(i,j);
}
return j;
}
private void swap(int i,int j){
int temp=a[i];
a[i]=a[j];
a[j]=temp;
}
private int[] a;
}
public class QuickSortTester {
public static void main(String args[]){
ArrayUtil au=new ArrayUtil();
int[] a=au.randomIntArray(20, 100);
QuickSort qs=new QuickSort(a);
qs.sort(0,19); //2 random numbers i put, cuz i don't understand it.
au.print(a);
}
}
}
If anyone can point out where its wrong, that will be great. Thanks in advance.