Concept Flow - Array sort functions
Start with array
Choose sort function
Compare elements
Swap if needed
Repeat until sorted
Return sorted array
The array is sorted by repeatedly comparing and swapping elements until the whole array is ordered.
<?php $arr = [3, 1, 4, 2]; sort($arr); print_r($arr); ?>
| Step | Array State | Action | Explanation | Output |
|---|---|---|---|---|
| 1 | [3, 1, 4, 2] | Start sorting | Initial array before sorting | |
| 2 | [1, 3, 4, 2] | Swap 3 and 1 | 3 > 1, swap to order ascending | |
| 3 | [1, 3, 4, 2] | Compare 3 and 4 | 3 < 4, no swap | |
| 4 | [1, 3, 2, 4] | Swap 4 and 2 | 4 > 2, swap to order ascending | |
| 5 | [1, 2, 3, 4] | Swap 3 and 2 | 3 > 2, swap to order ascending | |
| 6 | [1, 2, 3, 4] | Array sorted | No more swaps needed | [1, 2, 3, 4] |
| Variable | Start | After Step 2 | After Step 4 | After Step 5 | Final |
|---|---|---|---|---|---|
| arr | [3, 1, 4, 2] | [1, 3, 4, 2] | [1, 3, 2, 4] | [1, 2, 3, 4] | [1, 2, 3, 4] |
PHP array sort functions: - Use sort() to sort arrays ascending. - sort() changes the original array. - Elements are compared and swapped until sorted. - Output is the sorted array. - Works with numbers and strings.