Home Backend Development PHP Tutorial Detailed explanation of common PHP algorithms and data structure examples

Detailed explanation of common PHP algorithms and data structure examples

May 24, 2018 pm 05:02 PM
php data structure Detailed explanation

This article mainly introduces detailed examples of commonly used algorithms and data structures in PHP. Interested friends can refer to it. I hope it will be helpful to everyone.

The examples are as follows:

<?php
/**
 * Created by PhpStorm.
 * User: qishou
 * Date: 15-8-2
 * Time: 上午9:12
 */
header("content-type:text/html;charset=utf-8");
$arr = array(3,5,8,4,9,6,1,7,2);
echo implode(" ",$arr)."<br/>";
//---------------------------------------
//       常用排序算法
//---------------------------------------
//冒泡排序
function BubbleSort($arr){
  $length = count($arr);
  if($length<=1){
    return $arr;
  }
  for($i=0;$i<$length;$i++){
    for($j=$length-1;$j>$i;$j--){
      if($arr[$j]<$arr[$j-1]){
        $tmp = $arr[$j];
        $arr[$j] = $arr[$j-1];
        $arr[$j-1] = $tmp;
      }
    }
  }
  return $arr;
}
echo &#39;冒泡排序:&#39;;
echo implode(&#39; &#39;,BubbleSort($arr))."<br/>";

//快速排序
function QSort($arr){
  $length = count($arr);
  if($length <=1){
    return $arr;
  }
  $pivot = $arr[0];//枢轴
  $left_arr = array();
  $right_arr = array();
  for($i=1;$i<$length;$i++){//注意$i从1开始0是枢轴
    if($arr[$i]<=$pivot){
      $left_arr[] = $arr[$i];
    }else{
      $right_arr[] = $arr[$i];
    }
  }
  $left_arr = QSort($left_arr);//递归排序左半部分
  $right_arr = QSort($right_arr);//递归排序右半部份
  return array_merge($left_arr,array($pivot),$right_arr);//合并左半部分、枢轴、右半部分
}
echo "快速排序:";
echo implode(&#39; &#39;,QSort($arr))."<br/>";

//选择排序(不稳定)
function SelectSort($arr){
  $length = count($arr);
  if($length<=1){
    return $arr;
  }
  for($i=0;$i<$length;$i++){
    $min = $i;
    for($j=$i+1;$j<$length;$j++){
      if($arr[$j]<$arr[$min]){
        $min = $j;
      }
    }
    if($i != $min){
      $tmp = $arr[$i];
      $arr[$i] = $arr[$min];
      $arr[$min] = $tmp;
    }
  }
  return $arr;
}
echo "选择排序:";
echo implode(&#39; &#39;,SelectSort($arr))."<br/>";

//插入排序
function InsertSort($arr){
  $length = count($arr);
  if($length <=1){
    return $arr;
  }
  for($i=1;$i<$length;$i++){
    $x = $arr[$i];
    $j = $i-1;
    while($x<$arr[$j] && $j>=0){
      $arr[$j+1] = $arr[$j];
      $j--;
    }
    $arr[$j+1] = $x;
  }
  return $arr;
}
echo &#39;插入排序:&#39;;
echo implode(&#39; &#39;,InsertSort($arr))."<br/>";
//---------------------------------------
//       常用查找算法
//---------------------------------------
//二分查找
function binary_search($arr,$low,$high,$key){
  while($low<=$high){
    $mid = intval(($low+$high)/2);
    if($key == $arr[$mid]){
      return $mid+1;
    }elseif($key<$arr[$mid]){
      $high = $mid-1;
    }elseif($key>$arr[$mid]){
      $low = $mid+1;
    }
  }
  return -1;
}
$key = 6;
echo "二分查找{$key}的位置:";
echo binary_search(QSort($arr),0,8,$key);

//顺序查找
function SqSearch($arr,$key){
  $length = count($arr);
  for($i=0;$i<$length;$i++){
    if($key == $arr[$i]){
      return $i+1;
    }
  }
  return -1;
}
$key = 8;
echo "<br/>顺序常规查找{$key}的位置:";
echo SqSearch($arr,$key);
//---------------------------------------
//       常用数据结构
//---------------------------------------
//线性表的删除(数组实现)
function delete_array_element($arr,$pos){
  $length = count($arr);
  if($pos<1 || $pos>$length){
    return "删除位置出错!";
  }
  for($i=$pos-1;$i<$length-1;$i++){
    $arr[$i] = $arr[$i+1];
  }
  array_pop($arr);
  return $arr;
}
$pos = 3;
echo "<br/>除第{$pos}位置上的元素后:";
echo implode(&#39; &#39;,delete_array_element($arr,$pos))."<br/>";

/**
 * Class Node
 * PHP模拟链表的基本操作
 */
class Node{
  public $data = &#39;&#39;;
  public $next = null;
}
//初始化
function init($linkList){
  $linkList->data = 0; //用来记录链表长度
  $linkList->next = null;
}
//头插法创建链表
function createHead(&$linkList,$length){
  for($i=0;$i<$length;$i++){
    $newNode = new Node();
    $newNode->data = $i;
    $newNode->next = $linkList->next;//因为PHP中对象本身就是引用所以不用再可用“&”
    $linkList->next = $newNode;
    $linkList->data++;
  }
}
//尾插法创建链表
function createTail(&$linkList,$length){
  $r = $linkList;
  for($i=0;$i<$length;$i++){
    $newNode = new Node();
    $newNode->data = $i;
    $newNode->next = $r->next;
    $r->next = $newNode;
    $r = $newNode;
    $linkList->data++;
  }
}
//在指定位置插入指定元素
function insert($linkList,$pos,$elem){
  if($pos<1 && $pos>$linkList->data+1){
    echo "插入位置错误!";
  }
  $p = $linkList;
  for($i=1;$i<$pos;$i++){
    $p = $p->next;
  }
  $newNode = new Node();
  $newNode->data = $elem;
  $newNode->next = $p->next;
  $p->next = $newNode;
}
//删除指定位置的元素
function delete($linkList,$pos){
  if($pos<1 && $pos>$linkList->data+1){
    echo "位置不存在!";
  }
  $p = $linkList;
  for($i=1;$i<$pos;$i++){
    $p = $p->next;
  }
  $q = $p->next;
  $p->next = $q->next;
  unset($q);
  $linkList->data--;
}
//输出链表数据
function show($linkList){
  $p = $linkList->next;
  while($p!=null){
    echo $p->data." ";
    $p = $p->next;
  }
  echo &#39;<br/>&#39;;
}

$linkList = new Node();
init($linkList);//初始化
createTail($linkList,10);//尾插法创建链表
show($linkList);//打印出链表
insert($linkList,3,&#39;a&#39;);//插入
show($linkList);
delete($linkList,3);//删除
show($linkList);

/**
 * Class Stack
 * 用PHP模拟顺序栈的基本操作
 */
class Stack{
  //用默认值直接初始化栈了,也可用构造方法初始化栈
  private $top = -1;
  private $maxSize = 5;
  private $stack = array();

  //入栈
  public function push($elem){
    if($this->top >= $this->maxSize-1){
      echo "栈已满!<br/>";
      return;
    }
    $this->top++;
    $this->stack[$this->top] = $elem;
  }
  //出栈
  public function pop(){
    if($this->top == -1){
      echo "栈是空的!";
      return ;
    }
    $elem = $this->stack[$this->top];
    unset($this->stack[$this->top]);
    $this->top--;
    return $elem;
  }
  //打印栈
  public function show(){
    for($i=$this->top;$i>=0;$i--){
      echo $this->stack[$i]." ";
    }
    echo "<br/>";
  }
}

$stack = new Stack();
$stack->push(3);
$stack->push(5);
$stack->push(8);
$stack->push(7);
$stack->push(9);
$stack->push(2);
$stack->show();
$stack->pop();
$stack->pop();
$stack->pop();
$stack->show();

/**
 * Class Deque
 * 使用PHP实现双向队列
 */
class Deque{
  private $queue = array();
  public function addFirst($item){//头入队
    array_unshift($this->queue,$item);
  }
  public function addLast($item){//尾入队
    array_push($this->queue,$item);
  }
  public function removeFirst(){//头出队
    array_shift($this->queue);
  }
  public function removeLast(){//尾出队
    array_pop($this->queue);
  }
  public function show(){//打印
    foreach($this->queue as $item){
      echo $item." ";
    }
    echo "<br/>";
  }
}
$deque = new Deque();
$deque->addFirst(2);
$deque->addLast(3);
$deque->addLast(4);
$deque->addFirst(5);
$deque->show();

//PHP解决约瑟夫环问题
//方法一
function joseph_ring($n,$m){
  $arr = range(1,$n);
  $i = 0;
  while(count($arr)>1){
    $i=$i+1;
    $head = array_shift($arr);
    if($i%$m != 0){ //如果不是则重新压入数组
      array_push($arr,$head);
    }
  }
  return $arr[0];
}
//方法二
function joseph_ring2($n,$m){
  $r = 0;
  for($i=2;$i<=$n;$i++){
    $r = ($r+$m)%$i;
  }
  return $r + 1;
}
echo "<br/>".joseph_ring(60,5)."<br/>";
echo "<br/>".joseph_ring2(60,5)."<br/>";
Copy after login

The above is the entire content of this article, I hope it will be helpful to everyone learning helps.


Related recommendations:

Basic learning of php: PHP arrays and data structures

Data structure in PHPDetailed explanation of DS extension

phpData structureand sequential linked list Detailed explanation of the use of linear tables

The above is the detailed content of Detailed explanation of common PHP algorithms and data structure examples. For more information, please follow other related articles on the PHP Chinese website!

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

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

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)

PHP 8.4 Installation and Upgrade guide for Ubuntu and Debian PHP 8.4 Installation and Upgrade guide for Ubuntu and Debian Dec 24, 2024 pm 04:42 PM

PHP 8.4 brings several new features, security improvements, and performance improvements with healthy amounts of feature deprecations and removals. This guide explains how to install PHP 8.4 or upgrade to PHP 8.4 on Ubuntu, Debian, or their derivati

7 PHP Functions I Regret I Didn't Know Before 7 PHP Functions I Regret I Didn't Know Before Nov 13, 2024 am 09:42 AM

If you are an experienced PHP developer, you might have the feeling that you’ve been there and done that already.You have developed a significant number of applications, debugged millions of lines of code, and tweaked a bunch of scripts to achieve op

How To Set Up Visual Studio Code (VS Code) for PHP Development How To Set Up Visual Studio Code (VS Code) for PHP Development Dec 20, 2024 am 11:31 AM

Visual Studio Code, also known as VS Code, is a free source code editor — or integrated development environment (IDE) — available for all major operating systems. With a large collection of extensions for many programming languages, VS Code can be c

Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Apr 05, 2025 am 12:04 AM

JWT is an open standard based on JSON, used to securely transmit information between parties, mainly for identity authentication and information exchange. 1. JWT consists of three parts: Header, Payload and Signature. 2. The working principle of JWT includes three steps: generating JWT, verifying JWT and parsing Payload. 3. When using JWT for authentication in PHP, JWT can be generated and verified, and user role and permission information can be included in advanced usage. 4. Common errors include signature verification failure, token expiration, and payload oversized. Debugging skills include using debugging tools and logging. 5. Performance optimization and best practices include using appropriate signature algorithms, setting validity periods reasonably,

PHP Program to Count Vowels in a String PHP Program to Count Vowels in a String Feb 07, 2025 pm 12:12 PM

A string is a sequence of characters, including letters, numbers, and symbols. This tutorial will learn how to calculate the number of vowels in a given string in PHP using different methods. The vowels in English are a, e, i, o, u, and they can be uppercase or lowercase. What is a vowel? Vowels are alphabetic characters that represent a specific pronunciation. There are five vowels in English, including uppercase and lowercase: a, e, i, o, u Example 1 Input: String = "Tutorialspoint" Output: 6 explain The vowels in the string "Tutorialspoint" are u, o, i, a, o, i. There are 6 yuan in total

How do you parse and process HTML/XML in PHP? How do you parse and process HTML/XML in PHP? Feb 07, 2025 am 11:57 AM

This tutorial demonstrates how to efficiently process XML documents using PHP. XML (eXtensible Markup Language) is a versatile text-based markup language designed for both human readability and machine parsing. It's commonly used for data storage an

Explain late static binding in PHP (static::). Explain late static binding in PHP (static::). Apr 03, 2025 am 12:04 AM

Static binding (static::) implements late static binding (LSB) in PHP, allowing calling classes to be referenced in static contexts rather than defining classes. 1) The parsing process is performed at runtime, 2) Look up the call class in the inheritance relationship, 3) It may bring performance overhead.

What are PHP magic methods (__construct, __destruct, __call, __get, __set, etc.) and provide use cases? What are PHP magic methods (__construct, __destruct, __call, __get, __set, etc.) and provide use cases? Apr 03, 2025 am 12:03 AM

What are the magic methods of PHP? PHP's magic methods include: 1.\_\_construct, used to initialize objects; 2.\_\_destruct, used to clean up resources; 3.\_\_call, handle non-existent method calls; 4.\_\_get, implement dynamic attribute access; 5.\_\_set, implement dynamic attribute settings. These methods are automatically called in certain situations, improving code flexibility and efficiency.

See all articles