Wednesday, September 13, 2017

Bubble Sorting in PHP

Bubble Sort is the simplest sorting algorithm that works by repeatedly swapping the adjacent elements if they are in wrong order (Accending or Descending).

Example:

First Pass:
( 5 1 4 2 8 ) –> ( 1 5 4 2 8 ), Here, algorithm compares the first two elements, and swaps since 5 > 1.
( 1 5 4 2 8 ) –>  ( 1 4 5 2 8 ), Swap since 5 > 4
( 1 4 5 2 8 ) –>  ( 1 4 2 5 8 ), Swap since 5 > 2
( 1 4 2 5 8 ) –> ( 1 4 2 5 8 ), Now, since these elements are already in order (8 > 5), algorithm does not swap them.

Second Pass:
( 1 4 2 5 8 ) –> ( 1 4 2 5 8 )
( 1 4 2 5 8 ) –> ( 1 2 4 5 8 ), Swap since 4 > 2
( 1 2 4 5 8 ) –> ( 1 2 4 5 8 )
( 1 2 4 5 8 ) –>  ( 1 2 4 5 8 )

Now, the array is already sorted, but our algorithm does not know if it is completed. The algorithm needs one whole pass without any swap to know it is sorted.

Third Pass:
( 1 2 4 5 8 ) –> ( 1 2 4 5 8 )
( 1 2 4 5 8 ) –> ( 1 2 4 5 8 )
( 1 2 4 5 8 ) –> ( 1 2 4 5 8 )
( 1 2 4 5 8 ) –> ( 1 2 4 5 8 )

Implementation of this algorathim in PHP

$numbers=array(12,23,45,20,5,6,34,17,9,56);
$n=count($numbers);
for ($c = 0 ; $c < ( $n - 1 ); $c++)
{
 for ($d = 0 ; $d < ($n - $c - 1); $d++)
 {
   if ($numbers[$d] > $numbers[$d+1]) /* For decreasing order use < */
   {
  $swap = $numbers[$d];
  $numbers[$d]   = $numbers[$d+1];
  $numbers[$d+1] = $swap;
   }
 }
}

echo "Sorted list in ascending order <br />";
 
for ( $c = 0 ; $c < $n ; $c++ )
     echo $numbers[$c]." ";


Output : Output of the above code will be looking like this.

Sorted list in ascending order 
5 6 9 12 17 20 23 34 45 56


If you like this post don't forgot to leave a comment.

Chears 
Happy Coding :)

PHP logical Interview Questions and Answers that every developer should be know.


Question 1: What will be the results of $a and why?


$a = 2; 
function foo() { 
 $a = 3;  
} 

foo(); 
echo $a;
Answer: The output of above code will be "2" because here we are calling the function foo() but $a=3 scope will be only inside the function.

Question 2: What is the cause of this warning: 'Warning: Cannot modify header information - headers already sent', and what is a good practice to prevent it?
Answer: Cause: body data was sent, causing headers to be sent too.
Prevention: Be sure to execute header specific code first before you output any body data. Be sure you haven't accidentally sent out whitespace or any other characters.

Question 3: What is wrong with this query: "SELECT * FROM table WHERE id = $_POST[ 'id' ]"?
Answer:
  1. It is vulnarable to SQL injection. Never use user input directly in queries. Sanitize it first. Preferebly use prepared statements (PDO).
  2. Don't select all columns (*), but specify every single column. This is predominantly ment to prevent queries hogging up memory when for instance a BLOB column is added at some point in the future

Question 4: What is wrong with this if statement: if( !strpos( $haystack, $needle )?
Answer: strpos returns the index position of where it first found the $needle, which could be 0. Since 0 also resolves to false the solution is to use strict comparison: if( false !== strpos( $haystack, $needle ).

Question 5: What is the preferred way to write this if statement, and why?
if( 5 == $someVar ) or if( $someVar == 5 )
Answer: The former, as it prevents accidental assignment of 5 to $someVar when you forget to use 2 equalsigns ($someVar = 5), and will cause an error, the latter won't.

Question 6: Given this code:


function doSomething( &$arg )
{
    $return = $arg;
    $arg += 1;
    return $return;
}

$a = 3;
$b = doSomething( $a );

what is the value of $a and $b after the function call and why?
Answer: $a is 4 and $b is 3. The former because $arg is passed by reference, the latter because the return value of the function is a copy of (not a reference to) the initial value of the argument.

Question 7: What is the difference between public, protected and private in a class definition?
Answer: public makes a class member available to "everyone", protected makes the class member available to only itself and derived classes, private makes the class member only available to the class itself.

Question 8: What is wrong with this code:


class SomeClass
{
    protected $_someMember;

    public function __construct()
    {
        $this->_someMember = 1;
    }

    public static function getSomethingStatic()
    {
        return $this->_someMember * 5; // here's the catch
    }
}
Answer: Static methods don't have access to $this, because static methods can be executed without instantiating a class.

Question 9: What is the difference between an interface and an abstract class?
Answer: An interface defines a contract between an implementing class is and an object that calls the interface. An abstract class pre-defines certain behaviour for classes that will extend it. To a certain degree this can also be considered a contract, since it garantuees certain methods to exist.

Question 10: What is wrong with classes that predominantly define getters and setters, that map straight to it's internal members, without actually having methods that execute behaviour?
Answer: This might be a code smell since the object acts as an ennobled array, without much other use.

Question 11: What will be the results of $a and why?


$a = 2; 
function foo() { 
 $a += 3; 
 return $a; 
} 

$a = foo(); 
echo $a;
Answer: Its showing Notice: Undefined variable: a. Because in first line of function we are doing $a = $a +3 but here $a is not defined into the function its define outside of the function "foo".

Question 12: What would be the output of following:


$a = '1';
echo $b = &$a;
echo $c = "2$b";
Answer:  
  1.  1     // $b value will be 1
  2.  21  // $c value will be 21 as 2 is concatenated to the value of $b.

Question 13: What would be the output of the following?


var_dump(0123 == 123);
var_dump('0123' == 123);
var_dump('0123' === 123);
 Answer: 
  1. bool(false)   //  As number precede by 0 leads to an octal number.
  2. bool(true)    // as 0123 is enclosed in quotes so it would be concerted to it's numeric value which is 123 so it is true.
  3. bool(false)  // it's false as o123 is quoted and is string so they are not identical.Their data type is different. 
Question 14: What will be the output of the following:
Answer:  bool(true)   //  and operator works as OR because = operator has the precedence over and.

Question 15: What would be the output of following:

$array = array(
1 => "a",
"1" => "b",
1.5 => "c",
true => "d",
);
Answer:  Array ( [1] => d ) Explain : Here all keys will be type casted to number 1. But the value the array will hold will be of the data type whose precedence is higher precedence hierarchy in increment order is as follows: String("1")  => Number(1) => Float(1.5) => bool(true).  

So if we omit true element from array then result will be : Array ( [1] => c )  and so like that.

Question 16: Write a Program for Bubble sorting in accending order?
Answer: Click Here to See Answer

Question 17: How to calculate number of weaks between two dates using javascript?
Answer: Click Here to See Answer

Question 18: How to calulate number of months between two dates using javascript?
 Answer: Click Here to See Answer

Question 19: What is the difference between a HAVING CLAUSE and a WHERECLAUSE?
Answer: Click Here to See Answer

Question 20: How to swap two numbers without using third variable?
 Answer: Click Here to See Answer

Question 21: Write a program to find the biggest number in an array without using any array functions using PHP?
Answer: Click Here to See Answer

Question 22: Write a program to print fabonacci series using PHP? 
Answer: Click Here to See Answer

Question 23: Remove duplicate element from an array with out using built-in function using PHP? 
Answer: Click Here to See Answer

Question 24: How to Delete record from different table with out using sub query using mysql?
Answer: Click Here to See Answer

Question 25: How to Delete first or last index and value of an array using PHP?
Answer: Click Here to See Answer

Question 26: How to Get Second, Third, Forth or nth Largest Salery using Mysql or Sql? 
Answer: Click Here to See Answer

 

Please don't forgot to leave a comment if you like this post.

Chears :)
Best Of Luck For Your Interview.