forked from hacktoberfest17/programming
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathinsertion_sort.php
More file actions
40 lines (37 loc) · 1.53 KB
/
insertion_sort.php
File metadata and controls
40 lines (37 loc) · 1.53 KB
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
/**Function for insertion sort algorithm */
<?php
function insertion_Sort($my_array)
{
for($i=0;$i<count($my_array);$i++){
$val = $my_array[$i];
$j = $i-1;
while($j>=0 && $my_array[$j] > $val){
$my_array[$j+1] = $my_array[$j];
$j--;
}
$my_array[$j+1] = $val;
}
return $my_array;
}
$test_array = array(3, 0, 2, 5, -1, 4, 1);
echo "Original Array :\n";
echo implode(', ',$chk_array );
echo "\nSorted Array :\n";
print_r(insertion_Sort($chk_array));
?>
/** Chk Sample Output
*
* Original Array :
* 3, 0, 2, 5, -1, 4, 1
* Sorted Array :
* Array
* (
* [0] => -1
* [1] => 0
* [2] => 1
* [3] => 2
* [4] => 3
* [5] => 4
* [6] => 5
* )
*/