Home > Backend Development > PHP Tutorial > PHP implements common sorting algorithms

PHP implements common sorting algorithms

WBOY
Release: 2016-08-08 09:32:17
Original
1094 people have browsed it

Insertion Sort: Each time a record to be sorted is inserted into the appropriate position in the previously sorted sub-file according to its key size, until all records are inserted.

//插入排序(一维数组)
function insert_sort($arr)
{
	$count = count($arr);
	for($i=1; $i<$count; $i++)
	{
		$tmp = $arr[$i];
		$j = $i - 1;
		while($arr[$j] > $tmp)
		{
			$arr[$i] = $arr[$j];
			$arr[$j] = $tmp;
			$j--;
		}
	}
	return $arr;
}
Copy after login

Selection Sort: Each time the record with the smallest keyword is selected from the records to be sorted, and the order is placed at the end of the sorted sub-file until all records are sorted.

//选择排序(一维数组)
function selection_sort($arr)
{
	$count = count($arr);
	for($i=0; $i<$count; $i++)
	{
		$k = $i;
		for($j=$i+1; $j<$count; $j++)
		{
			if($arr[$k] > $arr[$j])
			{
				$k = $j;
			}

			if($k != $i)
			{
				$tmp = $arr[$i];
				$arr[$i] = $arr[$k];
				$arr[$k] = $tmp;
			}
		}
	}
	return $arr;
}
Copy after login

Bubble Sort (Bubble Sort): Compare the keywords of the records to be sorted pair by pair. If it is found that the order of the two records is reversed, they will be exchanged until there is no reverse record position.

//冒泡排序(一维数组)
//实际效果是:每次循环将数组中最小的值放置到数组的最前段,然后,下一次循环不再循环已放置正确数组值的键,以此类推
 function selection_sort($arr)
{
	$count = count($arr);
	if($count <= 0)
		return false;
	for($i=0; $i<$count; $i++)
	{
		for($j=$count-1; $j>$i; $j--)
		{
			if($arr[$j] < $array[$j-1])
			{
				$tmp = $arr[$j];
				$arr[$j] = $arr[$j-1];
				$arr[$j-1] = $tmp;
			}
		}
	}
	return $arr;
}
Copy after login

Quick sort: essentially the same as bubble sort, it is an application of exchange sort.

//快速排序(一维数组)
function quick_sort($arr)
{
	$count = count($arr);
	if($count <= 1)
		return $arr;
	$key = $arr[0];
	$left_arr = array();
	$right_arr = array();
	for($i=1; $i<$count; $i++)
	{
		if($arr[$i] <= $key)
			$left_arr[] = $arr[$i];
		else
			$right_arr[] = $arr[$i];
	}
	$left_arr = quick_sort($left_arr);
	$right_arr = quick_sort($right_arr);

	return array_merge($left_arr,array($arr), $right_arr);
}
Copy after login

The above introduces the implementation of common sorting algorithms in PHP, including aspects of the content. I hope it will be helpful to friends who are interested in PHP tutorials.

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template