Friday, October 25, 2013

IMPLEMENTATION OF QUICK SORT ALGORITHM IN JAVA.

/*
TOPIC: QUICK SORT ALGORITHM.
SEIT
DATE:27/9/2012
*/
import java.io.*;
class Sequence
{
BufferedReader br;
int a[];
int size,temp;
boolean flag;
long pivot;
int partition;
Sequence()
{
br = new BufferedReader ( new InputStreamReader(System.in));
flag=true;
}
void create()throws IOException
{
System.out.println("enter size of array: ");
size=Integer.parseInt(br.readLine());
a=new int[size];
insert();
}
void insert()throws IOException
{
System.out.println("INSERT THE ELEMENTS INTO THE ARRAY");
for(int i=0;i<size;i++)
a[i]=Integer.parseInt(br.readLine());
}
void QuickSort()
{ QuickSort(0,size-1);

}

void QuickSort(int l,int r)
{
if(r<l)
return;

partition=partition(l,r);
QuickSort(l,partition-1);
QuickSort(partition+1,r);




}
int partition(int l,int r)
{ int x=a[l];
int up=r;
int down=l;
while(down<up)
{ while(a[down]<=x && down<r)
{
down++;
}
while(a[up]>x)
{
up--;
}
if(down<up)
{
swap(down,up);
}

}
a[l]=a[up];
a[up]=x;
return up;

}

void swap(int up,int down)
{
//used addition swapping algorithm;
a[up]=a[down]+a[up];
a[down]=a[up]-a[down];
a[up]=a[up]-a[down];
}

void display()
{
for(int i=0;i<a.length;i++)
System.out.print(a[i]+" ");
System.out.println();
}
}
class QuickSort
{
public static void main(String args[])throws Exception
{
Sequence s=new Sequence();
s.create();
System.out.println("BEFORE SORTING");
s.display();
s.QuickSort();
System.out.println("AFTER SORTING");
s.display();
System.out.println("THANK U CODED BY TG");
}
}
/*
OUTPUT:
enter size of array:
8
INSERT THE ELEMENTS INTO THE ARRAY
15
444
52
85
96
4
285
26
BEFORE SORTING
15              444             52              85              96             285              26
AFTER SORTING
4               15              26              52              85             96               285             444
THANK U CODED BY TG
*/

No comments:

Post a Comment