Skip to main content

Php sorting algorithm

Bubble Sort

function bubbleSort(array $arr)
    {
$n = sizeof($arr);
for ($i = 1; $i < $n; $i++) {
for ($j = $n - 1; $j >= $i; $j--) {
if($arr[$j-1] > $arr[$j]) {
$tmp = $arr[$j - 1];
$arr[$j - 1] = $arr[$j];
$arr[$j] = $tmp;
}
}
}  
return $arr;
   }
   $arr = array(255,1,22,3,45,5);
$result = bubbleSort($arr);
print_r($result);
---------------------------------------------x----------------------------------------------

Selection Sort

function selectionSort(array $arr)
{
    $n = sizeof($arr);
    for ($i = 0; $i < $n; $i++) {
        $lowestValueIndex = $i;
        $lowestValue = $arr[$i];
        for ($j = $i + 1; $j < $n; $j++) {
            if ($arr[$j] < $lowestValue) {
                $lowestValueIndex = $j;
                $lowestValue = $arr[$j];
            }
        }

        $arr[$lowestValueIndex] = $arr[$i];
        $arr[$i] = $lowestValue;
    }
   
    return $arr;
}

// Example:
$arr = array(255,1,22,3,45,5);
$result = selectionSort($arr);
print_r($result);

Counting Sort

function countingSort(array $arr)
{
    $n = sizeof($arr);
    $p = array();
    $sorted = array();
   
    for ($i = 0; $i < $n; $i++) {
        $p[$i] = 0;
    }
   
    for ($i = 0; $i < $n; $i++) {
        for ($j = $i + 1; $j < $n; $j++) {
            if ($arr[$i] > $arr[$j]) {
                $p[$i]++;
            } else {
                $p[$j]++;
            }
        }
    }      
   
    for ($i = 0; $i < $n; $i++) {
        $sorted[$p[$i]] = $arr[$i];
    }
   
    return $sorted;
}

// Example:
$arr = array(255,1,22,3,45,5);
$result = countingSort($arr);
print_r($result);

Quicksort:

function quicksort(array $arr, $left, $right)
{
    $i = $left;
    $j = $right;
    $separator = $arr[floor(($left + $right) / 2)];
   
    while ($i <= $j) {
        while ($arr[$i] < $separator) {
            $i++;
        }
       
        while($arr[$j] > $separator) {
            $j--;
        }
       
        if ($i <= $j) {
            $tmp = $arr[$i];
            $arr[$i] = $arr[$j];
            $arr[$j] = $tmp;
            $i++;
            $j--;
        }
    }
   
    if ($left < $j) {
        $arr = quicksort($arr, $left, $j);
    }
   
    if ($right > $i) {
        $arr = quicksort($arr, $i, $right);
    }
   
    return $arr;
}

// Example:
$arr = array(20,12,4,13,5);
$result = quicksort($arr, 0, (sizeof($arr)-1));
print_r($result);

Shellsort:

function shellsort(array $arr)
{
    $n = sizeof($arr);
    $t = ceil(log($n, 2));
    $d[1] = 1;
    for ($i = 2; $i <= $t; $i++) {
        $d[$i] = 2 * $d[$i - 1] + 1;
    }
   
    $d = array_reverse($d);
    foreach ($d as $curIncrement) {
        for ($i = $curIncrement; $i < $n; $i++) {
            $x = $arr[$i];
            $j = $i - $curIncrement;
            while ($j >= 0 && $x < $arr[$j]) {
                $arr[$j + $curIncrement] = $arr[$j];
                $j = $j - $curIncrement;
            }
            $arr[$j + $curIncrement] = $x;
        }
    }
   
    return $arr;
}

// Example:
$arr = array(20,12,67,34,4,19,40,75,55,82,5,41,13,25,71);
$result = shellsort($arr);
print_r($result);

Heapsort (OOP version):

class Node
{
    private $_iData; // data item (key)
   
    public function __construct($key)
    {
        $this->_iData = $key;
    }
   
    public function getKey()
    {
        return $this->_iData;
    }
}

class Heap
{
    private $_heapArray;
    private $_currentSize;
   
    public function __construct()
    {
        $_heapArray = array();
        $this->_currentSize = 0;
    }
   
    /**
     * Delete item with max key (assumes non-empty list)
     */
    public function remove()
    {
        $root = $this->_heapArray[0];
        // put last element into root
        $this->_heapArray[0] = $this->_heapArray[--$this->_currentSize];
        // "sift" the root
        $this->bubbleDown(0);
       
        return $root; // return reference to removed root
    }
   
    /**
     * The "sift" process
     * (heap formation from our array of nodes)
     *
     * @param type $index
     */
    public function bubbleDown($index)
    {
        $largerChild = null;
        $top = $this->_heapArray[$index]; // save root
        while ($index < (int)($this->_currentSize/2)) { // not on bottom row
            $leftChild = 2 * $index + 1;
            $rightChild = $leftChild + 1;

            // find larger child
            if ($rightChild < $this->_currentSize
                    && $this->_heapArray[$leftChild] < $this->_heapArray[$rightChild]) // right child exists?
            {
                $largerChild = $rightChild;
            } else {
                $largerChild = $leftChild;
            }

            // top >= largerChild?
            if ($top->getKey() >= $this->_heapArray[$largerChild]->getKey()) {
                break;
            }

            // shift child up
            $this->_heapArray[$index] = $this->_heapArray[$largerChild];
            $index = $largerChild; // go down
        }

        $this->_heapArray[$index] = $top; // root to index
    }
   
    public function insertAt($index, Node $newNode)
    {
        $this->_heapArray[$index] = $newNode;
    }
   
    public function incrementSize()
    {
        $this->_currentSize++;
    }
   
    public function getSize()
    {
        return $this->_currentSize;
    }
   
    public function asArray()
    {
        $arr = array();
        for ($j = 0; $j < sizeof($this->_heapArray); $j++) {
            $arr[] = $this->_heapArray[$j]->getKey();
        }
       
        return $arr;
    }
}

function heapsort(Heap $Heap)
{  
    $size = $Heap->getSize();
    // "sift" all nodes,
    // except lowest level (it means only for half of nodes array)  
    // we skip lowest level, because lowest level don't have children
    for ($j = (int)($size/2) - 1; $j >= 0; $j--) { // make array into heap
        $Heap->bubbleDown($j);
    }
   

    for ($j = $size-1; $j >= 0; $j--) {      
        $BiggestNode = $Heap->remove();
        // use same nodes array
        // for sorted elements
        $Heap->insertAt($j, $BiggestNode);
    }
   
    return $Heap->asArray(); // get sorted array
}

// Example:
$arr = array(81,6,23,38,95,71,72,39,34,53);
$Heap = new Heap();
foreach ($arr as $key => $val) {
    $Node = new Node($val);
    $Heap->insertAt($key, $Node);
    $Heap->incrementSize();
}
$result = heapsort($Heap);
print_r($result);

Comments

Popular posts from this blog

Generate XML file in Cakephp

Steps to Generate XML file using CakePHP: Step-1 Enable to parse xml extension in config route.php file.     Router::parseExtensions('xml'); Step-2 Add Request Handler Component to the Controller    var $components = array(‘RequestHandler’); Step-3 Add controller Action For XML Generation in Post Controller     function generateXMLFile()     {         if ($this->RequestHandler->isXml()) { // check request type             $this->layout = 'empty'; // create an empty layout in app/views/layouts/empty.ctp              }        }  Add header code in empty layout <?php header('Content-type: text/xml');?> <?php echo $this->Xml->header(); ?> <?php echo $content_for_layout; ?> Step-4 Set up View To generate XML Create xml folder inside Posts vi...

How To Create Shortcodes In WordPress

We can create own shortcode by using its predified hooks add_shortcode( 'hello-world', 'techsudhir_hello_world_shortcode' ); 1. Write the Shortcode Function Write a function with a unique name, which will execute the code you’d like the shortcode to trigger: function techsudhir_hello_world_shortcode() {    return 'Hello world!'; } Example: [hello-world] If we were to use this function normally, it would return Hello world! as a string 2. Shortcode function with parameters function techsudhir_hello_world_shortcode( $atts ) {    $a = shortcode_atts( array(       'name' => 'world'    ), $atts );    return 'Hello ' . $a['name'] . !'; } Example: [hello-world name="Sudhir"] You can also call shortcode function in PHP using do_shortcode function Example: do_shortcode('[hello-world]');

How to replace plain URLs with links

Here we will explain how to replace Urls with links from string Using PHP $string ='Rajiv Uttamchandani is an astrophysicist, human rights activist, and entrepreneur. Academy, a nonprofit organization dedicated to providing a robust technology-centered education program for refugee and displaced youth around the world.  CNN Interview - https://www.youtube.com/watch?v=EtTwGke6Jtg   CNN Interview - https://www.youtube.com/watch?v=g7pRTAppsCc&feature=youtu.be'; $string = preg_replace('@(https?://([-\w\.]+)+(:\d+)?(/([\w/_\.%-=#]*(\?\S+)?)?)?)@', '<a href="$1">$1</a>', $string); Using Javascript <script> function linkify(inputText) {     var replacedText, replacePattern1, replacePattern2, replacePattern3;     //URLs starting with http://, https://, or ftp://     replacePattern1 = /(\b(https?|ftp):\/\/[-A-Z0-9+&@#\/%?=~_|!:,.;]*[-A-Z0-9+&@#\/%=~_|])/gim;     replacedText = inputT...