PHP Searching and Sorting Algorithm: Merge sort
Write a PHP program to sort a list of elements using Merge sort.
According to Wikipedia "Merge sort (also commonly spelled mergesort) is an O (n log n) comparison-based sorting algorithm. Most implementations produce a stable sort, which means that the implementation preserves the input order of equal elements in the sorted output."
Pictorial presentation - Merge search algorithm :
Sample Solution :
PHP Code :
Output:
Original Array : 100, 54, 7, 2, 5, 4, 1 Sorted Array : 1, 2, 4, 5, 7, 54, 100
Explanation:
In the exercise above,
- merge_sort($my_array): This function implements the merge sort algorithm recursively. It divides the input array into two halves, recursively sorts each half, and then merges them back together in sorted order.
- merge($left, $right): This function merges two sorted arrays ('$left' and '$right') into a single sorted array. It compares elements from both arrays and selects the smallest element to add to the result array. This is done until one of the arrays is empty.
- Finally, the code defines an example array '$test_array', prints the original array, calls "merge_sort()" to sort the array, and then prints the sorted array.
Flowchart :

Go to:
PREV : Write a PHP program to sort a list of elements using Patience sort.
NEXT : PHP Challenges Exercises Home.
PHP Code Editor:
Have another way to solve this solution? Contribute your code (and comments) through Disqus.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.