Skip to content

Commit 09da3c6

Browse files
authored
Created Insertion_Sort.php (#2805)
* Added Insertion_Sort.php * Update Insertion_Sort.php Co-authored-by: Ankita Saloni <[email protected]>
1 parent d62a3a1 commit 09da3c6

File tree

1 file changed

+64
-0
lines changed

1 file changed

+64
-0
lines changed

Insertion_Sort.php

+64
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,64 @@
1+
<?php
2+
3+
class InsertionSort
4+
{
5+
private $arr;
6+
public function __construct($arr)
7+
{
8+
$this->arr = $arr;
9+
}
10+
11+
//Printing the array
12+
public function printArray($array)
13+
{
14+
for($i = 0; $i < count($array); $i++)
15+
{
16+
echo $array[$i]." ";
17+
}
18+
}
19+
20+
//Sorting the array
21+
public function sort()
22+
{
23+
for($i = 1; $i < count($this->arr); $i++)
24+
{
25+
$temp = $this->arr[$i];
26+
while($i > 0 && $temp < $this->arr[$i-1])
27+
{
28+
$this->arr[$i] = $this->arr[$i-1];
29+
--$i;
30+
}
31+
$this->arr[$i] = $temp;
32+
}
33+
return $this->arr;
34+
}
35+
}
36+
37+
//Driver Code
38+
echo "<p> Implementing Insertion Sort Algorithm : </p>";
39+
$num = array();
40+
41+
for($i = 1; $i <= rand(1, 10); $i++)
42+
{
43+
$num[] = $i;
44+
}
45+
shuffle($num);
46+
47+
$is = new InsertionSort($num);
48+
49+
//Printing Unsorted array
50+
echo "<br>Unsorted Array : ";
51+
$is->printArray($num);
52+
53+
//Printing Sorted array
54+
echo "<br>Sorted Array : ";
55+
$is->printArray($is->sort());
56+
57+
/*
58+
Implementing Insertion Sort Algorithm :
59+
60+
Unsorted Array : 5 2 3 4 8 6 1 7
61+
62+
Sorted Array : 1 2 3 4 5 6 7 8
63+
*/
64+
?>

0 commit comments

Comments
 (0)