Skip to content
Related Articles

Related Articles

Improve Article

PHP | Ds\Deque sorted() Function

  • Last Updated : 14 Aug, 2019

The Ds\Deque::sorted() function is an inbuilt function in PHP which is used to return a copy of Deque which contains the element in the original Deque in increasing order.

Syntax:

public Ds\Deque::sorted( $comparator ) : Ds\Deque

Parameters: This function accepts single parameter $comparator which holds the comparator function to sorts the Deque.

Return Value: This function returns a Deque which contains elements of original Deque in the sorted order.

Below programs illustrate the Ds\Deque::sorted() function in PHP:



Program 1:




<?php
  
// Declare a deque
$deck = new \Ds\Deque([4, 5, 3, 2, 8, 1, 9]);
  
echo("Elements of Deque\n");
  
// Display the Deque elements
print_r($deck);
  
echo("Sorted Deque\n");
  
// Use sorted() function to 
// sort Deque elements
print_r($deck->sorted());
  
?>
Output:
Elements of Deque
Ds\Deque Object
(
    [0] => 4
    [1] => 5
    [2] => 3
    [3] => 2
    [4] => 8
    [5] => 1
    [6] => 9
)
Sorted Deque
Ds\Deque Object
(
    [0] => 1
    [1] => 2
    [2] => 3
    [3] => 4
    [4] => 5
    [5] => 8
    [6] => 9
)

Program 2:




<?php
  
// Declare a deque
$deck = new \Ds\Deque([4, 5, 3, 2, 8, 1, 9]);
  
echo("Elements of Deque\n");
  
// Display the Deque elements
print_r($deck);
  
// Use comparator function to sort elements
$deck = $deck->sorted(function($var1, $var2) {
    return $var1 <= $var2;
});
  
echo("Sorted Deque\n");
  
// Use sorted() function to 
// sort Deque elements
print_r($deck);
  
?>
Output:
Elements of Deque
Ds\Deque Object
(
    [0] => 4
    [1] => 5
    [2] => 3
    [3] => 2
    [4] => 8
    [5] => 1
    [6] => 9
)
Sorted Deque
Ds\Deque Object
(
    [0] => 9
    [1] => 8
    [2] => 5
    [3] => 4
    [4] => 3
    [5] => 2
    [6] => 1
)

Reference: http://php.net/manual/en/ds-deque.sorted.php




My Personal Notes arrow_drop_up
Recommended Articles
Page :