public
class
HeapSortTest {
public
static
int
[]
heap =
new
int
[]
{
1
,
3
,
7
,
5
,
2
,
8
,
4
,
6
,
10
,
9
};
public
static
void
main(String[] args) {
int
temp;
CreateHeap();
for
(
int
i = heap.length -
1
;
0
< i; i--) {
temp
= heap[
0
];
heap[
0
]
= heap[i];
heap[i]
= temp;
for
(
int
j =
0
;
j < heap.length; j++) {
System.out.print(heap[j]
+
"
"
);
}
System.out.println();
AdjustHeap(
0
,i);
}
}
public
static
void
AdjustHeap(
int
location,
int
unSortlength) {
int
temp;
int
tempLoc;
if
((tempLoc = (location +
1
)
*
2
)
< unSortlength) {
if
(heap[tempLoc] >= heap[tempLoc -
1
])
{
if
(heap[location] < heap[tempLoc]) {
temp
= heap[location];
heap[location]
= heap[tempLoc];
heap[tempLoc]
= temp;
AdjustHeap(tempLoc,unSortlength);
}
}
else
{
if
(heap[location] < heap[tempLoc -
1
])
{
temp
= heap[location];
heap[location]
= heap[tempLoc -
1
];
heap[tempLoc
-
1
]
= temp;
AdjustHeap(tempLoc
-
1
,unSortlength);
}
}
}
else
if
((tempLoc = (location +
1
)
*
2
-
1
)
< unSortlength) {
if
(heap[location] < heap[tempLoc]) {
temp
= heap[location];
heap[location]
= heap[tempLoc];
heap[tempLoc]
= temp;
AdjustHeap(tempLoc,unSortlength);
}
}
}
public
static
void
CreateHeap() {
for
(
int
i = heap.length -
1
;
i >=
0
;
i--) {
AdjustHeap(i,heap.length);
}
}
}