Algorithm
Partition(A,p,r)
{
x=A[r]
i=p-1
for(j=p to r-1)
{
if(A[j]<=x){
exchange A[i] with A[j]
}
}exchange A[i+1] with A[r]
return i+1
}
Quick_Sort(A,p,r)
{
if(p<r)
{
int q= partition(A,p,r)
Quick_Sort(A,p,q-1)
Quick_Sort(A,q+1,r)
}
}
Code
class quicksort{
public static void main(String[] args) {
int arr[]={3,2,1,5,8,1};
quick_sort(arr,0,arr.length-1);
for(int i:arr){
System.out.print(i+" ");
}
}//r is the pivot
static int partition(int arr[],int low,int r){
int x=arr[r];
int i=low-1;
for(int j=low;j<r-1;j++){
if(arr[j]<=x)
{
i++;
int temp=arr[j];
arr[j]=arr[i];
arr[i]=temp;
}
}
int temp=arr[r];
arr[r]=arr[i+1];
arr[i+1]=temp;
return i+1;
}
static int[] quick_sort(int arr[],int low,int pivot)
{
if(low<pivot){
int q=partition(arr, low, pivot);
quick_sort(arr, low, q-1);
quick_sort(arr,q+1,pivot);
}
return arr;
}
}
Output
1 1 2 3 5 8