TOPIC: HEAP SORT ALGORITHM.
DATE:3/10/2012
*/
import java.io.*;
class Sequence
{
int size;
int i;
int a[]=new int[25];
BufferedReader br;
Sequence()
{
br = new BufferedReader ( new InputStreamReader(System.in));
}
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 display()
{
for(int i=0;i<a.length;i++)
System.out.print(a[i]+" ");
System.out.println();
}
void HeapSort()
{
int n=size;
int i,elt,s,f,ivalue,pass=1;
for(i=1;i<n;i++)
{
elt=a[i];
s=i;
f=(s-1)/2;
while((s>0)&&(a[f]<elt))
{
a[s]=a[f];
s=f;
f=(s-1)/2;
}
a[s]=elt;
}
for(i=n-1;i>0;i--)
{
ivalue=a[i];
a[i]=a[0];
f=0;
if(i==1)
s=-1;
else
s=1;
if((i>2)&&(a[2]>a[1]))
s=2;
while((s>=0)&&(ivalue<a[s]))
{
a[f]=a[s];
f=s;
s=2*f+1;
if((s+1<=i-1)&&(a[s]<a[s+1]))
s=s+1;
if(s>(i-1))
s=-1;
}
a[f]=ivalue;
System.out.println();
}
}
}
class HeapSort
{
public static void main(String args[])throws IOException
{
Sequence s=new Sequence();
s.create();
System.out.println("BEFORE SORTING:");
s.display();
s.HeapSort();
System.out.println("AFTER SORTING:");
s.display();
}
}
/*
OUTPUT:
enter size of array:
8
INSERT THE ELEMENTS INTO THE ARRAY
25
4
65
9
555
1
23
12
BEFORE SORTING:
25 4 65 9 555 23 12
AFTER SORTING:
1 4 9 12 23 25 65 555
*/
No comments:
Post a Comment