Skip to content

Commit 25208c3

Browse files
author
Osama Sayed
committed
Adding radixsort
1 parent cb43f85 commit 25208c3

File tree

1 file changed

+72
-0
lines changed

1 file changed

+72
-0
lines changed

algorithms/sorting/radixsort.php

+72
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,72 @@
1+
<?php
2+
3+
/**
4+
* Description: Radix sort is a sorting algorithm that is used to sort numbers by
5+
* sorting them from the least significant digit to the most significant.
6+
*/
7+
8+
9+
$inputArray = [10, 15, 1, 60, 5, 100, 25, 50];
10+
radixSort($inputArray);
11+
var_dump($inputArray);
12+
13+
/**
14+
* Function to radix sort an array.
15+
*
16+
* @param array $inputArray array of elements to be sorted
17+
*/
18+
function radixSort(&$inputArray)
19+
{
20+
$maximumElement = $inputArray[0];
21+
$elementsCount = count($inputArray);
22+
$buckets = [];
23+
// create an array of 10 elements
24+
for ($i = 0; $i < 10; $i++) {
25+
$buckets[$i] = [];
26+
}
27+
28+
// get the maximum number in the input array
29+
for ($i = 1; $i < $elementsCount; $i++) {
30+
if ($inputArray[$i] > $maximumElement) {
31+
$maximumElement = $inputArray[$i];
32+
}
33+
}
34+
$digitsOfMaxElement = strlen($maximumElement);
35+
// adding leading zeros to all digits that are not of the same length of the largest element
36+
foreach ($inputArray as $inputIndex => $inputElement) {
37+
$inputArray[$inputIndex] = sprintf('%0'.$digitsOfMaxElement.'d', $inputElement);
38+
}
39+
40+
// start from the right most digit of the input elements
41+
$digitIndex = $digitsOfMaxElement -1;
42+
// we need to make digitsOfMaxElement passes
43+
for ($passIndex = 1; $passIndex <= $digitsOfMaxElement; $passIndex++) {
44+
// go through all elements in the inputArray
45+
foreach ($inputArray as $inputElement) {
46+
// get the digit number $digitIndex + 1
47+
$digit = $inputElement[$digitIndex];
48+
// put it in the corresponding bucket
49+
$buckets[$digit][] = $inputElement;
50+
}
51+
52+
$inputArray = [];
53+
// take the elements back from the buckets into the original array
54+
foreach ($buckets as $bucketArray) {
55+
foreach ($bucketArray as $bucketElement) {
56+
$inputArray[] = $bucketElement;
57+
}
58+
}
59+
60+
// re-initialize the bucket
61+
foreach ($buckets as $bucketIndex => $bucketArray) {
62+
$buckets[$bucketIndex] = [];
63+
}
64+
$digitIndex--;
65+
}
66+
67+
// remove the leading zero of elements by casting the elements to int
68+
foreach ($inputArray as &$element) {
69+
$element = (int) $element;
70+
}
71+
}
72+

0 commit comments

Comments
 (0)