PHP - Ds Deque::sort() Function



The PHP Ds\Deque::sort() function is used to sort the deque in-place, which means that the elements are sorted within the deque itself.

This function used an optional comparator function, which returns an integer that is less than, equal to, or greater than zero, if the first argument is respectively less than, equal to, or greater than the second.

Syntax

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

public Ds\Deque::sort(callable $comparator): void 

Following is the parameter of this function −

  • comparator − An optional comparator function returns an integer value.

Following is the syntax for the comparator function −

callback(mixed $a, mixed $b): int

Return value

This function does not return any value.

Example 1

The following program demonstrates the usage of the PHP Ds\Deque::sort() function −

<?php
   $deque = new \Ds\Deque([36, 18, 9, 27, 45]);
   echo "The deque elements are: \n";
   print_r($deque);
   #using sort() function
   $deque->sort();
   echo "The deque after sorting: \n";
   print_r($deque);
?>

Output

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

The deque elements are:
Ds\Deque Object
(
    [0] => 36
    [1] => 18
    [2] => 9
    [3] => 27
    [4] => 45
)
The deque after sorting:
Ds\Deque Object
(
    [0] => 9
    [1] => 18
    [2] => 27
    [3] => 36
    [4] => 45
))

Example 2

Following is another example of the PHP Ds\Deque::sort() function. We use this function to sort this deque (['c', 'e', 'a', 'b', 'd']) −

<?php
   $deque = new \Ds\Deque(['c', 'e', 'a', 'b', 'd']);
   echo "The deque elements are: \n";
   print_r($deque);
   #using sort() function
   $deque->sort();
   echo "The deque after sorting: \n";
   print_r($deque);
?>

Output

The above program produces the following output −

The deque elements are:
Ds\Deque Object
(
    [0] => c
    [1] => e
    [2] => a
    [3] => b
    [4] => d
)
The deque after sorting:
Ds\Deque Object
(
    [0] => a
    [1] => b
    [2] => c
    [3] => d
    [4] => e
)

Example 3

In the example below, we use this function to sort 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);
   $deque->sort();
   #using sort() function
   echo "The deque after sorting: \n";
   print_r($deque);
?>

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 deque after sorting:
Ds\Deque Object
(
    [0] => bark
    [1] => bear
    [2] => blank
    [3] => brass
    [4] => by
)
Advertisements