8000 Merge pull request #1148 from vidz-1/patch-1 · oo7dotcom/Algorithms@8b1cc3f · GitHub
[go: up one dir, main page]

Skip to content

Commit 8b1cc3f

Browse files
authored
Merge pull request VAR-solutions#1148 from vidz-1/patch-1
Create PHP
2 parents c66f44b + 2f429f0 commit 8b1cc3f

File tree

1 file changed

+72
-0
lines changed

1 file changed

+72
-0
lines changed

Sorting/Heapsort/php/heap_sort.php

Lines changed: 72 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,72 @@
1+
<?php
2+
3+
// Php program for implementation of Heap Sort
4+
5+
// To heapify a subtree rooted with node i which is
6+
// an index in arr[]. n is size of heap
7+
function heapify(&$arr, $n, $i)
8+
{
9+
$largest = $i; // Initialize largest as root
10+
$l = 2*$i + 1; // left = 2*i + 1
11+
$r = 2*$i + 2; // right = 2*i + 2
12+
13+
// If left child is larger than root
14+
if ($l < $n && $arr[$l] > $arr[$largest])
15+
$largest = $l;
16+
17+
// If right child is larger than largest so far
18+
if ($r < $n && $arr[$r] > $arr[$largest])
19+
$largest = $r;
20+
21+
// If largest is not root
22+
if ($largest != $i)
23+
{
24+
$swap = $arr[$i];
25+
$arr[$i] = $arr[$largest];
26+
$arr[$largest] = $swap;
27+
28+
// Recursively heapify the affected sub-tree
29+
heapify($arr, $n, $largest);
30+
}
31+
}
32+
33+
// main function to do heap sort
34+
function heapSort(&$arr, $n)
35+
{
36+
// Build heap (rearrange array)
37+
for ($i = $n / 2 - 1; $i >= 0; $i--)
38+
heapify($arr, $n, $i);
39+
40+
// One by one extract an element from heap
41+
for ($i = $n-1; $i > 0; $i--)
42+
{
43+
// Move current root to end
44+
$temp = $arr[0];
45+
$arr[0] = $arr[$i];
46+
$arr[$i] = $temp;
47+
48+
// call max heapify on the reduced heap
49+
heapify($arr, $i, 0);
50+
}
51+
}
52+
53+
/* A utility function to print array of size n */
54+
function printArray(&$arr, $n)
55+
{
56+
for ($i = 0; $i < $n; ++$i)
57+
echo ($arr[$i]." ") ;
58+
59+
}
60+
61+
// Driver program
62+
$arr = array(12, 11, 13, 5, 6, 7);
63+
$n = sizeof($arr)/sizeof($arr[0]);
64+
65+
heapSort($arr, $n);
66+
67+
echo 'Sorted array is ' . "\n";
68+
69+
printArray($arr , $n);
70+
71+
// This code is contributed by Shivi_Aggarwal
72+
?>

0 commit comments

Comments
 (0)
0