-
Notifications
You must be signed in to change notification settings - Fork 0
/
heap-sort
88 lines (84 loc) · 1.36 KB
/
heap-sort
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
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
import java.util.Scanner;
public class heapsortTEST
{
public static void main(String[] args){
System.out.println("enter 8 numbers");
Scanner sc = new Scanner(System.in);
int[] a = new int [8];
for (int i=0; i<8; i++)
{
a[i] = sc.nextInt();
}
a = heapsort.k(a);
for(int i=0; i<8; i++)
{
System.out.println(a[i]);
}
}
}
class max_heapify
{
public static void m(int[] A, int i)
{
int l = 2*i;
int r = 2*i+1;
int largest = 0;
/* you need to compare both the parent, the left child and the right child */
if(l<= A.length && A[l-1]>A[i-1])
{
largest = l;
}
else
{
largest = i;
}
if(r<=A.length && A[r-1]>A[largest-1])
{
largest = r;
}
if(largest != i)
{
int temp = A[i-1];
A[i-1] = A[largest-1];
A[largest-1] = temp;
max_heapify.m(A, largest);
}
}
}
class build_max_heap
{
public static void n(int[] A)
{
for(int i=(int)Math.floor(A.length/2); i>=1; i--)
{
max_heapify.m(A, i);
}
}
}
class heapsort
{
public static int[] k(int[] A)
{
build_max_heap.n(A);
int[] B = new int[8];
for(int i=A.length; i>=2; i--)
{
int temp = A[0];
A[0] = A[i-1];
A[i-1] = temp;
B[i-1] = A[i-1];
int[] C = new int[i-1];
for(int x=0; x<i-1; x++)
{
C[x] = A[x];
}
max_heapify.m(C,1);
for(int y=0; y<i-1; y++)
{
A[y] = C[y];
}
}
B[0] = A[0];
return B;
}
}