-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathheapsort.java
60 lines (56 loc) · 1.19 KB
/
heapsort.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
import java.util.*;
class heapsort
{
public static void swap(int arr[],int i,int j)
{
int temp=arr[i];
arr[i]=arr[j];
arr[j]=temp;
}
public static void heapsorting(int arr[],int n)
{
for (int i=n-1; i>=0; i--)
{
swap(arr,0,i);
// call max heapify on the reduced heap
heapify(arr, 0, i);
for(int j=0;j<n;j++)
System.out.print(arr[j]+" ");
System.out.println("**");
}
}
public static void heapify(int A[],int i,int size){
int max=i;
int l=(2*i)+1,r=(2*i)+2;
if(l<size && A[l]>A[max])
max=l;
if(r<size && A[r]>A[max])
max=r;
if(max!=i){
swap(A,max,i);
heapify(A,max,size);
}
}
public static void buildheap()
{
Scanner sc=new Scanner(System.in);
int n=sc.nextInt();
int arr[]=new int[n];
for(int i=0;i<n;i++)
{
arr[i]=sc.nextInt();
}
for(int i=(n/2);i>=0;i--)
heapify(arr,i,n);
for(int i=0;i<n;i++)
System.out.print(arr[i]+" ");
System.out.println("build");
heapsorting(arr,n);
//for(int i=0;i<n;i++)
//System.out.println(arr[i]);
}
public static void main(String args[])
{
buildheap();
}
}