-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathInsertion Sort - Part 1.php
55 lines (41 loc) · 1012 Bytes
/
Insertion Sort - Part 1.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
<?php
/**
* @author: syed ashraf ullah
* Date: 21/04/2020
*/
// Complete the insertionSort1 function below.
function insertionSort1($n, $arr)
{
while (--$n > 0) {
$copy = -1;
// Lower index is greter value, need to swap
if ($arr[$n] < $arr[$n-1]) {
$copy = $arr[$n];
$arr[$n] = $arr[$n-1];
// Print aurrent array
foreach ($arr as $value) {
echo $value.' ';
}
$arr[$n-1] = $copy;
// new line
echo PHP_EOL;
}
}
// Final sorted array
foreach ($arr as $value) {
echo $value.' ';
}
}
/**
* Sample input #1
*/
// $n = 5;
// $arr = array(2, 4, 6, 8, 3);
// insertionSort1($n, $arr);
// return;
$stdin = fopen("php://stdin", "r");
fscanf($stdin, "%d\n", $n);
fscanf($stdin, "%[^\n]", $arr_temp);
$arr = array_map('intval', preg_split('/ /', $arr_temp, -1, PREG_SPLIT_NO_EMPTY));
insertionSort1($n, $arr);
fclose($stdin);