/*
QuickSort:
This sort can be done in different ways ..........
I have taken Pivot as middle element.
you can take any element as Pivot.
Author: itafiz@gmail.com
*/
class SortQuick
{
public static void main(String[]args)
{
int i;
int array[] = {12,9,4,99,1};
System.out.println("Elements Before Sort:\n");
for(i = 0; i < array.length; i++)
System.out.print( array[i]+" ");
System.out.println();
quickSort(array,0,array.length-1);
System.out.println("Elements Before Sort:\n");
for(i = 0; i < array.length; i++)
System.out.print( array[i]+" ");
System.out.println();
}
public static void quickSort(int a[],int low, int len)
{
if(low>=len) return; // checking if length of the array is Zero.
int l=low,n=len; //initialization
int piv=a[(l+n)/2]; // middle element
while(l<n)//--------------------------1
{ /**
moving upto less than pivot value from start.
*/
while(l<n && a[l]<piv)
l++;
/**
moving upto greater than pivot value from end.
*/
while(l<n && a[n]>piv)
n--;
/**
swap in order to move least elements to left and maximum to right
of the pivot.
*/
if(l<n){
int tem = a[l];
a[l]=a[n];
a[n]=tem; }
}// end of while loop----------1
if(n<l)// checking start and end index(start must be less than end otherwise swap)
{
int t = l;l=n;n=t;
}
quickSort(a,low,l);// sort left part of the array.
quickSort(a,l==low?l+1:l,len); //sorting right part of the array
}
}
0 Comments