FazBrowse GitHub Viewer
|
Trending
|
URL:
|
Home
Tools:
[Download Repo ZIP]
[View Raw Code]
[Original HTTPS Page]
JavaScript/Sorts/HeapSort.js at master · TheAlgorithms/JavaScript · GitHub
Uh oh!
There was an error while loading.
Please reload this page
.
TheAlgorithms
/
JavaScript
Public
Uh oh!
There was an error while loading.
Please reload this page
.
Notifications
You must be signed in to change notification settings
Fork
5.8k
Star
34.2k
Code
Issues
21
Pull requests
192
Actions
Projects
Wiki
Security and quality
0
Insights
Additional navigation options
Code
Issues
Pull requests
Actions
Projects
Wiki
Security and quality
Insights
Expand file tree
Breadcrumbs
JavaScript
/
Sorts
/
HeapSort.js
Copy path
More file actions
More file actions
Latest commit
History
History
History
54 lines (46 loc) · 1.45 KB
Breadcrumbs
JavaScript
/
Sorts
/
HeapSort.js
Copy path
File metadata and controls
54 lines (46 loc) · 1.45 KB
Raw
Copy raw file
Download raw file
Open symbols panel
Edit and raw actions
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
/*
* Build a max heap out of the array. A heap is a specialized tree like
* data structure that satisfies the heap property. The heap property
* for max heap is the following: "if P is a parent node of C, then the
* key (the value) of node P is greater than the key of node C"
* Source: https://en.wikipedia.org/wiki/Heap_(data_structure)
*/
/* eslint no-extend-native: ["off", { "exceptions": ["Object"] }] */
Array
.
prototype
.
heapify
=
function
(
index
,
heapSize
)
{
let
largest
=
index
const
leftIndex
=
2
*
index
+
1
const
rightIndex
=
2
*
index
+
2
if
(
leftIndex
<
heapSize
&&
this
[
leftIndex
]
>
this
[
largest
]
)
{
largest
=
leftIndex
}
if
(
rightIndex
<
heapSize
&&
this
[
rightIndex
]
>
this
[
largest
]
)
{
largest
=
rightIndex
}
if
(
largest
!==
index
)
{
const
temp
=
this
[
largest
]
this
[
largest
]
=
this
[
index
]
this
[
index
]
=
temp
this
.
heapify
(
largest
,
heapSize
)
}
}
/*
* Heap sort sorts an array by building a heap from the array and
* utilizing the heap property.
* For more information see: https://en.wikipedia.org/wiki/Heapsort
*/
export
function
heapSort
(
items
)
{
const
length
=
items
.
length
for
(
let
i
=
Math
.
floor
(
length
/
2
)
-
1
;
i
>
-
1
;
i
--
)
{
items
.
heapify
(
i
,
length
)
}
for
(
let
j
=
length
-
1
;
j
>
0
;
j
--
)
{
const
tmp
=
items
[
0
]
items
[
0
]
=
items
[
j
]
items
[
j
]
=
tmp
items
.
heapify
(
0
,
j
)
}
return
items
}
// Implementation of heapSort
// const ar = [5, 6, 7, 8, 1, 2, 12, 14]
// heapSort(ar)
Back
|
FazBrowse Home
|
New Git URL