PHP Program to Merge two Sorted Arrays
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.
PHP Program to Merge two Sorted Arrays
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 ); ?> |
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 ); ?> |
Merged Sorted Array: 1, 2, 3, 4, 5, 6, 7, 8
Recommend
About Joyk
Aggregate valuable and interesting links.
Joyk means Joy of geeK