PHP - Ds Sequence::sort() 函式



PHP 的 Ds\Sequence::sort() 函式用於對序列的元素進行就地排序。術語 “就地” 表示該函式在現有序列中對元素進行排序,而無需為新序列分配額外的記憶體。

預設情況下,元素按“升序”排序。但是,您可以提供一個可選的比較器函式以自定義順序(例如降序)對序列進行排序。

語法

以下是 PHP Ds\Sequence::sort() 函式的語法:

abstract public Ds\Sequence::sort(callable $comparator = ?): void

引數

以下是此函式的引數:

  • comparator - 比較函式比較元素,並且必須返回一個整數值。

以下是 comparator 函式的語法:

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

返回值

此函式不返回值。

示例 1

如果省略比較器函式,則 Ds\Sequence::sort() 函式預設情況下會按升序對序列元素進行排序,如下所示

<?php 
   $seq = new \Ds\Vector([2, 7, 1, 9, 6, 3]); 
   echo "The original sequence: \n";
   print_r($seq);
   echo "The sequence after sort: \n";
   #using sort() function
   $seq->sort();
   print_r($seq); 
?>

輸出

以上程式產生以下輸出:

The original sequence:
Ds\Vector Object
(
    [0] => 2
    [1] => 7
    [2] => 1
    [3] => 9
    [4] => 6
    [5] => 3
)
The sequence after sort:
Ds\Vector Object
(
    [0] => 1
    [1] => 2
    [2] => 3
    [3] => 6
    [4] => 7
    [5] => 9
)

示例 2

以下是 PHP Ds\Sequence::sort() 函式的另一個示例。我們使用此函式使用比較器函式按降序對當前序列 ([3, 5, 11, 2, 6, 1, 4, 9]) 元素進行排序:

<?php 
   $seq = new \Ds\Vector([3, 5, 11, 2, 6, 1, 4, 9]);
   echo "The sequence before sorting: \n";
   print_r($seq);
   #using sort() function
   $seq->sort(function($x, $y) { 
      return $y <=> $x; #sorting in descending order
   }); 
   echo "The sequence after sorting: \n";
   print_r($seq);
?>

輸出

執行上述程式後,將顯示以下輸出:

The sequence before sorting:
Ds\Vector Object
(
    [0] => 3
    [1] => 5
    [2] => 11
    [3] => 2
    [4] => 6
    [5] => 1
    [6] => 4
    [7] => 9
)
The sequence after sorting:
Ds\Vector Object
(
    [0] => 11
    [1] => 9
    [2] => 6
    [3] => 5
    [4] => 4
    [5] => 3
    [6] => 2
    [7] => 1
)
php_function_reference.htm
廣告