File: /home/saiesh/ADS/Assignment No 11/ads11.java
Page 1 of 2
import java.util.Scanner;
public class ads11
{
private static int N;
public static void sort(int arr[])
{
heapify(arr);
for(int i=N;i>0;i--)
{
swap(arr,0,i);
N=N-1;
maxheap(arr,0);
}
}
public static void heapify(int arr[])
{
N=arr.length-1;
for(int i=N/2;i>=0;i--)
maxheap(arr,i);
}
public static void maxheap(int arr[],int i)
{
int left=2*i;
int right=2*i+1;
int max=i;
if(left<=N&&arr[left]>arr[i])
max=left;
if(right<=N&&arr[right]>arr[max])
max=right;
if(max!=i)
{
swap(arr,i,max);
maxheap(arr,max);
}
}
public static void swap(int arr[],int i,int j)
{
int temp;
temp=arr[i];
arr[i]=arr[j];
arr[j]=temp;
}
public static void main(String[] args)
{
Scanner scan=new Scanner(System.in);
System.out.println("\t\tHeap Sort Test");
int i,n;
System.out.print("\nEnter number of integer elements\t:");
n=scan.nextInt();
int arr[]=new int[n];
System.out.print("Enter "+n+" integer elements\t\t:");
for(i=0;i<n;i++)
arr[i]=scan.nextInt();
sort(arr);
System.out.print("Elements after sorting\t\t\t:");
for(i=0;i<n;i++)
System.out.print(arr[i]+ " " );
System.out.println();
}
}File: /home/saiesh/ADS/Assignment No 11/ads11.java
/*
OUTPUT
saiesh@saiesh :~$ javac ads11.java
saiesh@saiesh :~$ java ads11
Heap Sort Test
Enter number of integer elements
Enter 5 integer elements
Elements after sorting
saiesh@saiesh :~$ */
:5
:98 52 75 14 65
:14 52 65 75 98
Page 2 of 2
Page 1 of 2
import java.util.Scanner;
public class ads11
{
private static int N;
public static void sort(int arr[])
{
heapify(arr);
for(int i=N;i>0;i--)
{
swap(arr,0,i);
N=N-1;
maxheap(arr,0);
}
}
public static void heapify(int arr[])
{
N=arr.length-1;
for(int i=N/2;i>=0;i--)
maxheap(arr,i);
}
public static void maxheap(int arr[],int i)
{
int left=2*i;
int right=2*i+1;
int max=i;
if(left<=N&&arr[left]>arr[i])
max=left;
if(right<=N&&arr[right]>arr[max])
max=right;
if(max!=i)
{
swap(arr,i,max);
maxheap(arr,max);
}
}
public static void swap(int arr[],int i,int j)
{
int temp;
temp=arr[i];
arr[i]=arr[j];
arr[j]=temp;
}
public static void main(String[] args)
{
Scanner scan=new Scanner(System.in);
System.out.println("\t\tHeap Sort Test");
int i,n;
System.out.print("\nEnter number of integer elements\t:");
n=scan.nextInt();
int arr[]=new int[n];
System.out.print("Enter "+n+" integer elements\t\t:");
for(i=0;i<n;i++)
arr[i]=scan.nextInt();
sort(arr);
System.out.print("Elements after sorting\t\t\t:");
for(i=0;i<n;i++)
System.out.print(arr[i]+ " " );
System.out.println();
}
}File: /home/saiesh/ADS/Assignment No 11/ads11.java
/*
OUTPUT
saiesh@saiesh :~$ javac ads11.java
saiesh@saiesh :~$ java ads11
Heap Sort Test
Enter number of integer elements
Enter 5 integer elements
Elements after sorting
saiesh@saiesh :~$ */
:5
:98 52 75 14 65
:14 52 65 75 98
Page 2 of 2
Comments
Post a Comment