Quick Sort Implementation In Java
Sorting Techniques
import java.io.*;
class quick
{
public static int a[];
public static void main(String args[]) throws IOException
{
int a[],n;
BufferedReader b=new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter size of array = ");
n = Integer.parseInt(b.readLine());
a = new int[n];
System.out.println("Enter values = ");
for(int i=0;i<n;i++)
a[i] = Integer.parseInt(b.readLine());
quick_sort(a,0,n-1);
for(int i=0;i<n;i++)
System.out.println("\n sorted array is"+a[i]);
}
public static void quick_sort(int x[],int lb, int ub)
{
int j;
if(lb>=ub)
return;
j=partition(x,lb,ub);
quick_sort(x,lb,j-1);
quick_sort(x,j+1,ub);
}
public static int partition(int x[],int lb,int ub)
{
int a,temp,up,down;
a=x[lb];
up=ub;
down=lb;
while(down<up)
{
while(x[down]<=a && down<up)
down++;
while(x[up]>a)
up--;
if(down<up)
{
temp=x[up];
x[up]=x[down];
x[down]=temp;
}
}
x[lb]=x[up];
x[up]=a;
return up;
}
}
class quick
{
public static int a[];
public static void main(String args[]) throws IOException
{
int a[],n;
BufferedReader b=new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter size of array = ");
n = Integer.parseInt(b.readLine());
a = new int[n];
System.out.println("Enter values = ");
for(int i=0;i<n;i++)
a[i] = Integer.parseInt(b.readLine());
quick_sort(a,0,n-1);
for(int i=0;i<n;i++)
System.out.println("\n sorted array is"+a[i]);
}
public static void quick_sort(int x[],int lb, int ub)
{
int j;
if(lb>=ub)
return;
j=partition(x,lb,ub);
quick_sort(x,lb,j-1);
quick_sort(x,j+1,ub);
}
public static int partition(int x[],int lb,int ub)
{
int a,temp,up,down;
a=x[lb];
up=ub;
down=lb;
while(down<up)
{
while(x[down]<=a && down<up)
down++;
while(x[up]>a)
up--;
if(down<up)
{
temp=x[up];
x[up]=x[down];
x[down]=temp;
}
}
x[lb]=x[up];
x[up]=a;
return up;
}
}
You Might Also Like :