Home Backend Development PHP Tutorial PHP implements common sorting algorithms

PHP implements common sorting algorithms

Aug 08, 2016 am 09:32 AM
arr count function return sort

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.

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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Chat Commands and How to Use Them
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Detailed explanation of the usage of return in C language Detailed explanation of the usage of return in C language Oct 07, 2023 am 10:58 AM

The usage of return in C language is: 1. For functions whose return value type is void, you can use the return statement to end the execution of the function early; 2. For functions whose return value type is not void, the function of the return statement is to end the execution of the function. The result is returned to the caller; 3. End the execution of the function early. Inside the function, we can use the return statement to end the execution of the function early, even if the function does not return a value.

How to implement drag-and-drop sorting and drag-and-drop operations in uniapp How to implement drag-and-drop sorting and drag-and-drop operations in uniapp Oct 19, 2023 am 09:39 AM

Uniapp is a cross-platform development framework. Its powerful cross-end capabilities allow developers to develop various applications quickly and easily. It is also very simple to implement drag-and-drop sorting and drag-and-drop operations in Uniapp, and it can support drag-and-drop operations of a variety of components and elements. This article will introduce how to use Uniapp to implement drag-and-drop sorting and drag-and-drop operations, and provide specific code examples. The drag-and-drop sorting function is very common in many applications. For example, it can be used to implement drag-and-drop sorting of lists, drag-and-drop sorting of icons, etc. Below we list

What does function mean? What does function mean? Aug 04, 2023 am 10:33 AM

Function means function. It is a reusable code block with specific functions. It is one of the basic components of a program. It can accept input parameters, perform specific operations, and return results. Its purpose is to encapsulate a reusable block of code. code to improve code reusability and maintainability.

Explore the underlying principles and algorithm selection of the C++sort function Explore the underlying principles and algorithm selection of the C++sort function Apr 02, 2024 pm 05:36 PM

The bottom layer of the C++sort function uses merge sort, its complexity is O(nlogn), and provides different sorting algorithm choices, including quick sort, heap sort and stable sort.

What is the execution order of return and finally statements in Java? What is the execution order of return and finally statements in Java? Apr 25, 2023 pm 07:55 PM

Source code: publicclassReturnFinallyDemo{publicstaticvoidmain(String[]args){System.out.println(case1());}publicstaticintcase1(){intx;try{x=1;returnx;}finally{x=3;}}}#Output The output of the above code can simply conclude: return is executed before finally. Let's take a look at what happens at the bytecode level. The following intercepts part of the bytecode of the case1 method, and compares the source code to annotate the meaning of each instruction in

The difference between counta and count The difference between counta and count Nov 20, 2023 am 10:01 AM

The Count function is used to count the number of numbers in a specified range. It ignores text, logical values, and null values, but counts empty cells. The Count function only counts the number of cells that contain actual numbers. The CountA function is used to count the number of non-empty cells in a specified range. It not only counts cells containing actual numbers, but also counts the number of non-empty cells containing text, logical values, and formulas.

Sort array using Array.Sort function in C# Sort array using Array.Sort function in C# Nov 18, 2023 am 10:37 AM

Title: Example of using the Array.Sort function to sort an array in C# Text: In C#, array is a commonly used data structure, and it is often necessary to sort the array. C# provides the Array class, which has the Sort method to conveniently sort arrays. This article will demonstrate how to use the Array.Sort function in C# to sort an array and provide specific code examples. First, we need to understand the basic usage of the Array.Sort function. Array.So

What is the purpose of the 'enumerate()' function in Python? What is the purpose of the 'enumerate()' function in Python? Sep 01, 2023 am 11:29 AM

In this article, we will learn about enumerate() function and the purpose of “enumerate()” function in Python. What is the enumerate() function? Python's enumerate() function accepts a data collection as a parameter and returns an enumeration object. Enumeration objects are returned as key-value pairs. The key is the index corresponding to each item, and the value is the items. Syntax enumerate(iterable,start) Parameters iterable - The passed in data collection can be returned as an enumeration object, called iterablestart - As the name suggests, the starting index of the enumeration object is defined by start. if we ignore

See all articles