Skip to content

Commit

Permalink
[solved] Correctness and the Loop Invariant
Browse files Browse the repository at this point in the history
  • Loading branch information
ashraf789 committed Apr 22, 2020
1 parent 9629425 commit 3a88815
Show file tree
Hide file tree
Showing 2 changed files with 46 additions and 10 deletions.
36 changes: 36 additions & 0 deletions Correctness and the Loop Invariant.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
<?php
/**
* @author: syed ashraf ullah
* date: 22/04/2020
* problem: https://www.hackerrank.com/challenges/correctness-invariant/problem
*/

function insertionSort(&$arr){
for($i=0;$i<count($arr);$i++){
$val = $arr[$i];
$j = $i-1;
while($j>=0 && $arr[$j] > $val){
$arr[$j+1] = $arr[$j];
$j--;
}
$arr[$j+1] = $val;
}
}
/**
* Sample #1
*/
// $arr = array(7, 4, 3, 5, 6, 2);
// insertionSort($arr);
// foreach($arr as $value) {
// print $value." ";
// }
// return;
$handle = fopen ("php://stdin","r");
$t = fgets($handle);
$arr = explode(' ', fgets($handle));

insertionSort($arr);
foreach($arr as $value) {
print $value." ";
}
?>
20 changes: 10 additions & 10 deletions Insertion Sort - Part 2.php
Original file line number Diff line number Diff line change
Expand Up @@ -11,15 +11,15 @@ function insertionSort1($n, $arr)
while (++$i < $n) {

$k = $i;

$val = $arr[$k];

// Sort from current index
while (--$k >= 0 && $arr[$k] > $arr[$k+1]) {
$copy = $arr[$k];
$arr[$k] = $arr[$k+1];

$arr[$k+1] = $copy;
while (--$k >= 0 && $val < $arr[$k]) {
$arr[$k+1] = $arr[$k];
}

$arr[$k+1] = $val;

// Print current array
foreach ($arr as $value) {
echo $value.' ';
Expand All @@ -36,16 +36,16 @@ function insertionSort1($n, $arr)
/**
* Sample input #1
*/
// $n = 6;
// $arr = array(1, 4, 3, 5, 6, 2);
$n = 6;
$arr = array(1, 4, 3, 5, 6, 2);

/**
* Sample input #2
*/
// $n = 7;
// $arr = array(3, 4, 7, 5, 6, 2, 1);
// insertionSort1($n, $arr);
// return;
insertionSort1($n, $arr);
return;

$stdin = fopen("php://stdin", "r");

Expand Down

0 comments on commit 3a88815

Please sign in to comment.