Optimized Heap Sort
In the previous section's heap sort, we allocated extra space to build the heap and sort it. In this section, we optimize and use in-place heap sort.
For a maximum heap, first swap the data at the starting position with the value at the end of the array, so the largest element is at the end of the array. Then perform a shift down operation on the W element to regenerate the maximum heap, then swap the newly generated maximum with the second-to-last position of the entire array, so the second-to-last position holds the second-largest data. This process continues in the same way.
The entire process can be represented as follows:

Java Example Code
Source code package download:Download
src/runoob/heap/HeapSort.java file code:
package
runoob.heap
;
import
runoob.sort.SortTestHelper
;
/**
* In-place heap sort
*/
public
class
HeapSort
<
T
extends
Comparable
{
public
static
void
sort
(
Comparable
[
]
arr
)
{
int
n
=arr.
length
;
// Note that at this point our heap is 0-indexed
// Start from (index of the last element - 1)/2
// Index of the last element = n-1
for
(
int
i
=
(
n
1
1
)
/
2
;
i
=
0
;
i
--
)
shiftDown
(
arr, n, i
)
;
for
(
int
i
=
n
1
;
i
0
;
i
--
)
{
swap
(
arr,
0
, i
)
;
shiftDown
(
arr, i,
0
)
;
}
}
// Swap the two elements with indices i and j in the heap
private
static
void
swap
(
Object
[
]
arr,
int
i,
int
j
)
{
Object
t
=
arr
[
i
]
;
arr
[
i
]
=
arr
[
j
]
;
arr
[
j
]
=
t
;
}
// Original shiftDown process
private
static
void
shiftDown
(
Comparable
[
]
arr,
int
n,
int
k
)
{
while
(
2
k
1
<
n
)
{// Left child node
int
j
=
2
k
1
;
// Right child node is larger than the left child node
if
(
j
1
<
n
&&
arr
[
j
1
].
compareTo
(
arr
[
j
]
)
0
)
j
+=
1
;
// Larger than both child nodes
if
(
arr
[
k
]
.
compareTo
(
arr
[
j
]
)
=
0
)
break
;
// Swap the values of the original node and the child node
swap
(
arr, k, j
)
;
k
=
j
;
}
}
// Test HeapSort
public
static
void
main
(
String
[
]
args
)
{
int
N
=
100
;
Integer
[
]
arr
=
SortTestHelper.
generateRandomArray
(
N,
0
,
100000
)
;
sort
(
arr
)
;
// Gradually take the data out of heapify using extractMax
// The order of taking out should be from largest to smallest
for
(
int
i
=
0
;
i
<
N
;
i
++
)
{
System
.
out
.
(
arr
[
i
]
" "
)
;
}
// Ensure the arr array is arranged from largest to smallest
for
(
int
i
=
1
;
i
<
N
;
i
++
)
assert
arr
[
i
1
]
=
arr
[
i
]
;
}
}