Skip to content

Instantly share code, notes, and snippets.

@harmlessprince
Last active May 12, 2021 15:23
Show Gist options
  • Save harmlessprince/84ea0e417561052c79deb1e34d130925 to your computer and use it in GitHub Desktop.
Save harmlessprince/84ea0e417561052c79deb1e34d130925 to your computer and use it in GitHub Desktop.
This function takes in two set of arrays, merges them and sort them using the quick sort algorithm. It returns a new array of the merged arrays in ascending order. It has a worst case time complexity of O(nlog(n)) and space complexity of 0(log(n))
<?php
function SortAndMergeArrayOfStudentAges($firstArray, $secondArray)
{
if (gettype($firstArray) != 'array' && gettype($secondArray) != 'array') {
return [];
}
if (gettype($firstArray) == 'array' && gettype($secondArray) != 'array') {
return quickSort($firstArray);
}
if (gettype($firstArray) != 'array' && gettype($secondArray) == 'array') {
return quickSort($secondArray);
}
return quickSort(array_merge($firstArray, $secondArray));
}
function quickSort($array)
{
quickSortHelper($array, 0, count($array) - 1);
return $array;
}
function quickSortHelper(&$array, $startIndex, $endIndex)
{
if ($startIndex >= $endIndex) {
return;
}
$pivotIndex = $startIndex;
$leftIndex = $startIndex + 1;
$rightIndex = $endIndex;
while ($rightIndex >= $leftIndex) {
if ($array[$leftIndex] > $array[$pivotIndex] && $array[$rightIndex] < $array[$pivotIndex]) {
swap($array, $leftIndex, $rightIndex);
}
if ($array[$leftIndex] <= $array[$pivotIndex]) {
$leftIndex += 1;
}
if ($array[$rightIndex] >= $array[$pivotIndex]) {
$rightIndex -= 1;
}
}
swap($array, $pivotIndex, $rightIndex);
$leftSubArrayIsSmaller = $rightIndex - (1 - $startIndex) < $endIndex - ($rightIndex + 1);
if ($leftSubArrayIsSmaller) {
quickSortHelper($array, $startIndex, $rightIndex - 1);
quickSortHelper($array, $rightIndex + 1, $endIndex);
} else {
quickSortHelper($array, $rightIndex + 1, $endIndex);
quickSortHelper($array, $startIndex, $rightIndex - 1);
}
}
function swap(&$array, $a, $b)
{
list($array[$a], $array[$b]) = array($array[$b], $array[$a]);
}
$firstArray = [13,15,19];
$secondArray = [11, 13, 18];
// print_r(mergeStudentAges($firstArray, $secondArray));
print_r(SortAndMergeArrayOfStudentAges($firstArray, $secondArray));
@harmlessprince
Copy link
Author

harmlessprince commented May 12, 2021

Boss, you are right. 😂

Their is always one thing.....

I have updated the solution to accommodate that now.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment