Saturday, November 16, 2024
Google search engine
HomeLanguagesPHP | DsDeque sort() Function

PHP | Ds\Deque sort() Function

The Ds\Deque::sort() function is an inbuilt function in PHP which is used to sort the Deque in place by arranging the elements in increasing order.

Syntax:

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

Parameters::This function accepts single parameter $comparator which holds the function to decides how to sort the elements. It helps in customizing the sort function.

Return Value: This function does not return any value.

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

Program 1:




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


Output:

Elements of Deque
Ds\Deque Object
(
    [0] => 5
    [1] => 6
    [2] => 3
    [3] => 2
    [4] => 7
    [5] => 1
)
Sorted Deque
Ds\Deque Object
(
    [0] => 1
    [1] => 2
    [2] => 3
    [3] => 5
    [4] => 6
    [5] => 7
)

Program 2:




<?php
  
// Declare a deque
$deck = new \Ds\Deque([5, 6, 3, 2, 7, 1]);
  
echo("Elements of Deque\n");
  
// Display the Deque elements
print_r($deck);
  
// comparator to sort in reverse order
$deck->sort(function($first, $second) {
    return $first <= $second;
});
   
echo("Sorted Deque\n");
  
// Display the Deque elements
print_r($deck);;
  
?>


Output:

Elements of Deque
Ds\Deque Object
(
    [0] => 5
    [1] => 6
    [2] => 3
    [3] => 2
    [4] => 7
    [5] => 1
)
Sorted Deque
Ds\Deque Object
(
    [0] => 7
    [1] => 6
    [2] => 5
    [3] => 3
    [4] => 2
    [5] => 1
)

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

Whether you’re preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape, neveropen Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we’ve already empowered, and we’re here to do the same for you. Don’t miss out – check it out now!

RELATED ARTICLES

Most Popular

Recent Comments