forked from subho57/Algo_Ds_Notes
-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathInsertion_Sort.php
64 lines (53 loc) · 1.25 KB
/
Insertion_Sort.php
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
<?php
class InsertionSort
{
private $arr;
public function __construct($arr)
{
$this->arr = $arr;
}
//Printing the array
public function printArray($array)
{
for($i = 0; $i < count($array); $i++)
{
echo $array[$i]." ";
}
}
//Sorting the array
public function sort()
{
for($i = 1; $i < count($this->arr); $i++)
{
$temp = $this->arr[$i];
while($i > 0 && $temp < $this->arr[$i-1])
{
$this->arr[$i] = $this->arr[$i-1];
--$i;
}
$this->arr[$i] = $temp;
}
return $this->arr;
}
}
//Driver Code
echo "<p> Implementing Insertion Sort Algorithm : </p>";
$num = array();
for($i = 1; $i <= rand(1, 10); $i++)
{
$num[] = $i;
}
shuffle($num);
$is = new InsertionSort($num);
//Printing Unsorted array
echo "<br>Unsorted Array : ";
$is->printArray($num);
//Printing Sorted array
echo "<br>Sorted Array : ";
$is->printArray($is->sort());
/*
Implementing Insertion Sort Algorithm :
Unsorted Array : 5 2 3 4 8 6 1 7
Sorted Array : 1 2 3 4 5 6 7 8
*/
?>