PHP Professional এবং Zend Certified PHP Engineer (ZCPE ) Course এ সীমিত সংখ্যক আসন বাকি আছে। আগ্রহীদেরকে অতিসত্বর মাসুদ আলম স্যার এর সাথে যোগাযোগ করার জন্য অনুরোধ করা যাচ্ছে। স্যার এর মোবাইল নম্বর : ০১৭২২ ৮১ ৭৫ ৯১

Insertion Sort with PHP – Part 1

Sorting
One common task for computers is to sort data. For example, people might want to see all their files on a computer sorted by size. Since sorting is a simple problem with many different possible solutions, it is often used to introduce the study of algorithms.

Insertion Sort
These challenges will cover Insertion Sort, a simple and intuitive sorting algorithm. We will first start with an already sorted list.

Insert element into sorted list
Given a sorted list with an unsorted number in the rightmost cell, can you write some simple code to insert into the array so that it remains sorted?

Print the array every time a value is shifted in the array until the array is fully sorted. The goal of this challenge is to follow the correct order of insertion sort.

Guideline: You can copy the value of to a variable and consider its cell “empty”. Since this leaves an extra cell empty on the right, you can shift everything over until can be inserted. This will create a duplicate of each value, but when you reach the right spot, you can replace it with .

Input Format
There will be two lines of input:

  • – the size of the array
  • – the unsorted array of integers

Output Format
On each line, output the entire array every time an item is shifted in it.

Constraints

Sample Input

5
2 4 6 8 3

Sample Output

2 4 6 8 8 
2 4 6 6 8 
2 4 4 6 8 
2 3 4 6 8 

Explanation

is removed from the end of the array.
In the st line , so is shifted one cell to the right.
In the nd line , so is shifted one cell to the right.
In the rd line , so is shifted one cell to the right.
In the th line , so is placed at position .

Task

Complete the method insertionSort which takes in one parameter:

  • – an array with the value in the right-most cell.

 

Solutions with PHP


function  insertionSort( $ar) {

//get array last value
$end=end($ar);

//use global m value
global $m; $c=$m; $t=$m-1;
$flag=false;
for($i=0;$i<$c;$i++){
$t>0 ? $t-- : $t=-1;
$temp=[];
for($j=0;$j<$c-1;$j++){
if($j==0 && $t<0){
$temp[]= $end;
}
$temp[]= $ar[$j];
if( $j == $t){
if($ar[$t] > $end){
$temp[]= $ar[$j];
}else{
$temp[]= $end;
$flag=true;
}
}
}
for($k=0;$k<count($temp);$k++){
echo $temp[$k] . ' ';
}
if($flag==true){break;}
echo "\n";
}

}
$fp = fopen("php://stdin", "r");
fscanf($fp, "%d", $m);
$ar = array();
$s=fgets($fp);
$ar = explode(" ", $s);
for($i=0;$i < count($ar);$ar[$i++]+=0);
insertionSort($ar);

 

Hackerrank problem link

Click here

 

 

 

I am PHP problem solver at Hackerrank. I am preparing myself for PHP zend certification exam with Masud Alam sir.
I have completed few websites using LARAVEL, also have experience on WORDPRESS.

Leave a Reply

Your email address will not be published. Required fields are marked *