PHP - Ds Deque::sorted() Function



The PHP Ds\Deque::sorted() function is used to retrieve a sorted copy of the current deque. To do this, the function uses an optional comparator which is a comparison function.

If the first argument is less than, equal to, or greater than the second, the function returns an integer less than, equal to, or greater than zero.

Syntax

Following is the syntax of the PHP Ds\Deque::sorted() function −

public Ds\Deque::sorted(callable $comparator = ?): Ds\Deque 

Parameters

This function accepts an optional parameter named 'comparator' function, which is described below −

  • comparator − The comparison function must return an integer.

Return value

This method returns a sorted copy of the deque.

Example 1

The following is the basic example of the PHP Ds\Deque::sorted() function −

<?php
   $deque = new \Ds\Deque(['c', 'e', 'a', 'b', 'd']);
   echo "The original deque: \n";
   print_r($deque);
   echo "The sorted copy of a deque: \n";
   #using sorted() function
   print_r($deque->sorted());
?>

Output

The above program produces the following output −

The original deque:
Ds\Deque Object
(
    [0] => c
    [1] => e
    [2] => a
    [3] => b
    [4] => d
)
The sorted copy of a deque:
Ds\Deque Object
(
    [0] => a
    [1] => b
    [2] => c
    [3] => d
    [4] => e
)

Example 2

Following is another example of thePHP Ds\Deque::sorted()function. We use this function to retrieve a sorted copy to this deque ([4, 2, 1, 5, 3]) −

<?php
   $deque = new \Ds\Deque([4, 2, 1, 5, 3]);
   echo "The original deque: \n";
   print_r($deque);
   echo "The sorted copy of a deque: \n";
   print_r($deque->sorted(function($first, $second) {
       return $first <= $second;
   }));
?>

Output

After executing the above program, the following output will be displayed −

The original deque:
Ds\Deque Object
(
    [0] => 4
    [1] => 2
    [2] => 1
    [3] => 5
    [4] => 3
)
The sorted copy of a deque:
Ds\Deque Object
(
    [0] => 5
    [1] => 4
    [2] => 3
    [3] => 2
    [4] => 1
)

Example 3

In the example below, we use the sorted() function to retrieve a sorted copy of this deque(["by", "bear", "blank", "brass", "bark"]) as follows −

<?php
   $deque = new \Ds\Deque(["by", "bear", "blank", "brass", "bark"]);
   echo "The original deque: \n";
   print_r($deque);
   echo "The sorted copy of a deque: \n";
   print_r($deque->sorted());
?>

Output

On executing the above program, it will generate the following output −

The original deque:
Ds\Deque Object
(
    [0] => by
    [1] => bear
    [2] => blank
    [3] => brass
    [4] => bark
)
The sorted copy of a deque:
Ds\Deque Object
(
    [0] => bark
    [1] => bear
    [2] => blank
    [3] => brass
    [4] => by
)
Advertisements