Quick Sort in PHP

Here, you can use this article to accomplish the task of the Quick Sort in PHP. You can go directly to an article to do this task directly without wasting your time.

Quick sort algorithm was developed using the divide and conquer approach and it comes under the comparison algorithm category. This is also known as partition-exchange sort.

This algorithm splits the array into two sub-arrays based on the pivot position and performs the sort operation recursively till there are no more sub-arrays exist. Quick sort is the easiest way of sorting technique, but it’s not efficient on large data sets.

  • First element of the array
  • Last element of the array
  • Random element of the array
  • Median index element of the array
Quick Sort in PHP

Quick Sort in PHP

<?php
function quick_sort($my_array)
 {
	$loe = $gt = array();
	if(count($my_array) < 2)
	{
		return $my_array;
	}
	$pivot_key = key($my_array);
	$pivot = array_shift($my_array);
	foreach($my_array as $val)
	{
		if($val <= $pivot)
		{
			$loe[] = $val;
		}elseif ($val > $pivot)
		{
			$gt[] = $val;
		}
	}
	return array_merge(quick_sort($loe),array($pivot_key=>$pivot),quick_sort($gt));
}
 
$my_array = array(53, 25, 36, 75, -48, 62, 19);
echo 'Original Array : '.implode(',',$my_array).'\n';
$my_array = quick_sort($my_array);
echo 'Sorted Array : '.implode(',',$my_array);
?>

Read Also: Quick Sort In Python

Read Also: Polymorphism In PHP

Output of Quick Sort in PHP

Original Array : 53, 25, 36, 75, -48, 62, 19
                             
Sorted Array : -48, 19, 25, 36, 53, 62, 75

Conclusion

I hope this article helps you to know the Quick Sort in PHP. If you encounter any issues let me know via 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