7

PHP Program to Merge two Sorted Arrays

 9 months ago
source link: https://www.geeksforgeeks.org/php-program-to-merge-two-sorted-arrays/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

PHP Program to Merge two Sorted Arrays

Discuss
Courses

Given two sorted arrays, i.e. arr1, and arr2, the task is to merge both sorted arrays and make a single sorted array.

Examples:

Input: arr1 = [1, 3, 5, 7, 8]
arr2 = [2, 3, 4, 5, 6]
Output: [1, 2, 3, 3, 4, 5, 6, 7, 8]

There are two methods to merge both arrays, these are:

Using Loop

Here, we iterate through both arrays and compare array elements to merge them into a new sorted array.

Example:

<?php
function mergeArrays($arr1, $arr2) {
$mergedArray = [];
$i = $j = 0;
while ($i < count($arr1) && $j < count($arr2)) {
if ($arr1[$i] < $arr2[$j]) {
$mergedArray[] = $arr1[$i];
$i++;
} else {
$mergedArray[] = $arr2[$j];
$j++;
}
}
while ($i < count($arr1)) {
$mergedArray[] = $arr1[$i];
$i++;
}
while ($j < count($arr2)) {
$mergedArray[] = $arr2[$j];
$j++;
}
return $mergedArray;
}
$arr1 = [1, 3, 5, 7];
$arr2 = [2, 4, 6, 8];
$newArray = mergeArrays($arr1, $arr2);
echo "Merged Sorted Array: " . implode(", ", $newArray);
?>
Output
Merged Sorted Array: 1, 2, 3, 4, 5, 6, 7, 8

Using array_merge() Function

The array_merge() function is used to merge two or more arrays into a single array. After merging the both arrays, we use sort() function to sort the merged array in ascending order.

Example:

<?php
function mergeArrays($arr1, $arr2) {
$mergedArray = array_merge($arr1, $arr2);
sort($mergedArray);
return $mergedArray;
}
$arr1 = [1, 3, 5, 7];
$arr2 = [2, 4, 6, 8];
$newArray = mergeArrays($arr1, $arr2);
echo "Merged Sorted Array: " . implode(", ", $newArray);
?>
Output
Merged Sorted Array: 1, 2, 3, 4, 5, 6, 7, 8
Whether you're preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape, GeeksforGeeks 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!
Last Updated : 12 Dec, 2023
Like Article
Save Article

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK