Merge Sort in PHP

Using this tutorial you will successfully complete the task of Merge Sort in PHP Let’s go

Merge Sort is a complex and fast sorting algorithm that repeatedly divides an un-sorted section into two equal sub-sections, sorts them separately, and merges them correctly.

Merge Sort in PHP

Merge Sort in PHP

<?php
function merge_sort($my_array){
	if(count($my_array) == 1 ) return $my_array;
	$mid = count($my_array) / 2;
    $left = array_slice($my_array, 0, $mid);
    $right = array_slice($my_array, $mid);
	$left = merge_sort($left);
	$right = merge_sort($right);
	return merge($left, $right);
}
function merge($left, $right){
	$res = array();
	while (count($left) > 0 && count($right) > 0){
		if($left[0] > $right[0]){
			$res[] = $right[0];
			$right = array_slice($right , 1);
		}else{
			$res[] = $left[0];
			$left = array_slice($left, 1);
		}
	}
	while (count($left) > 0){
		$res[] = $left[0];
		$left = array_slice($left, 1);
	}
	while (count($right) > 0){
		$res[] = $right[0];
		$right = array_slice($right, 1);
	}
	return $res;
}
$test_array = array(87, 92, 56, 46, 77, 68, 39);
echo "Original Array : ";
echo implode(', ',$test_array );
echo "\nSorted Array :";
echo implode(', ',merge_sort($test_array))."\n";
?>

Requirements:

  • You are required to use Merge Sort algorithm when sorting the numbers.
  • You are required to implement the algorithm in PHP language.

Read Also: Merge Sort in Python

Output of Merge Sort in PHP

Original Array : 87, 92, 56, 46, 77, 68, 39
                            
Sorted Array : 39, 46, 56, 68, 77, 87, 92 

Read Also: Merge Sort In C++

Read Also: Quick Sort in PHP

Final Words

We hope you find the Merge Sort in PHP. What to do if there are any issues with this article? Then ask through the comment section.

Hi, I'm Ranjith a full-time Blogger, YouTuber, Affiliate Marketer, & founder of Coding Deekshi. Here, I post about programming to help developers.

Share on:

Leave a Comment