Home > Backend Development > PHP Tutorial > Commonly used algorithms for PHP interviews (recommended)_php examples

Commonly used algorithms for PHP interviews (recommended)_php examples

WBOY
Release: 2016-08-04 08:56:44
Original
927 people have browsed it

1. Bubble sort

Basic idea:

Scan the array to be sorted from back to front (in reverse order) multiple times. When it is found that the order of two adjacent values ​​​​is inconsistent with the rules required for sorting, the two values ​​​​are exchanged. In this way, the smaller (larger) values ​​will gradually move from the back to the front.

//Bubble sort

<&#63;php

  function mysort($arr)
  {
    for($i = 0; $i < count($arr); $i++)
    {
      $isSort = false;
      for ($j=0; $j< count($arr) - $i - 1; $j++) 
      {
        if($arr[$j] < $arr[$j+1])
        {
          $isSort = true;
          $temp = $arr[$j];
          $arr[$j] = $arr[$j+1];
          $arr[$j+1] = $temp ;
        }
      }
      if($isSort)
      {
        break;
      }
    }
    return $arr;
  }

  $arr = array(3,1,2);
  var_dump(mysort($arr));
&#63;>
Copy after login

2. Quick sort

Basic idea:

Select an element in the array (mostly the first one) as the ruler, scan the array once, and sort the elements smaller than the ruler before the ruler, and sort all the elements larger than the ruler after the ruler, and recurse each subsequence Divide into smaller sequences until all sequences are in the same order.

//Quick sort

<&#63;php
  //快速排序
    function quick_sort($arr) 
    {
      //先判断是否需要继续进行
      $length = count($arr);
      if($length <= 1) 
      {
        return $arr;
      }
    
      $base_num = $arr[0];//选择一个标尺 选择第一个元素

      //初始化两个数组
      $left_array = array();//小于标尺的
      $right_array = array();//大于标尺的
      for($i=1; $i<$length; $i++) 
      {      //遍历 除了标尺外的所有元素,按照大小关系放入两个数组内
        if($base_num > $arr[$i]) 
        {
          //放入左边数组
          $left_array[] = $arr[$i];
        } 
        else 
        {
          //放入右边
          $right_array[] = $arr[$i];
        }
      }
      //再分别对 左边 和 右边的数组进行相同的排序处理方式
      //递归调用这个函数,并记录结果
      $left_array = quick_sort($left_array);
      $right_array = quick_sort($right_array);
      //合并左边 标尺 右边
      return array_merge($left_array, array($base_num), $right_array);
    }

    $arr = array(3,1,2);
    var_dump(quick_sort($arr));

&#63;>
Copy after login

Three and two point search

Basic idea:

Assume that the data is sorted in ascending order. For a given value x, start the comparison from the middle position of the sequence. If the current position value is equal to x, the search is successful; if x is less than the current position value, search in the first half of the sequence; If x is greater than the current position value, continue searching in the second half of the sequence until it is found. (Use when the amount of data is large)

//Binary search

<&#63;php
  //二分查找
  function bin_search($arr,$low,$high,$k)
  {
    if($low <= $high)
    {
      $mid = intval(($low + $high)/2);
      if($arr[$mid] == $k)
      {
        return $mid;
      }
      else if($k < $arr[$mid])
      {
        return bin_search($arr,$low,$mid-1,$k);
      }
      else
      {
        return bin_search($arr,$mid+1,$high,$k);
      }
    }
    return -1;
  }

  $arr = array(1,2,3,4,5,6,7,8,9,10);

  print(bin_search($arr,0,9,3));
&#63;>
Copy after login

4. Sequential search

Basic idea:

Start from the first element of the array and search downwards one by one. If there is an element consistent with the target, the search is successful; if there is still no target element until the last element, the search fails.

//Sequential search 

<&#63;php
  //顺序查找
  function seq_search($arr,$n,$k)
  {
    $array[$n] = $k;
    for($i = 0;$i < $n; $i++)
    {
      if($arr[$i] == $k)
      {
        break;
      }
    }

    if($i < $n)
    {
      return $i;
    }
    else
    {
      return -1;
    }
  }
&#63;>
Copy after login

5. Write a function that can traverse all files and subfolders under a file

<&#63;php  
  function my_scandir($dir)
  {
    $files = array();
    if($handle = opendir($dir))
    {
      while (($file = readdir($handle))!== false) 
      {
        if($file != '..' && $file != '.')
        {
          if(is_dir($dir."/".$file))
          {
            $files[$file]=my_scandir($dir."/".$file);
          }
          else
          {
            $files[] = $file;
          }
        }
      }

      closedir($handle);
      return $files;
    }
  }

  var_dump(my_scandir('../'));
&#63;>
Copy after login

6. Write a function to extract the file extension from a standard URL as efficiently as possible

<&#63;php
  function getExt($url)
  {
    $arr = parse_url($url);//parse_url解析一个 URL 并返回一个关联数组,包含在 URL 中出现的各种组成部分
    //'scheme' => string 'http' (length=4)
    //'host' => string 'www.sina.com.cn' (length=15)
    //'path' => string '/abc/de/fg.php' (length=14)
    //'query' => string 'id=1' (length=4)
    $file = basename($arr['path']);// basename函数返回路径中的文件名部分
    $ext = explode('.', $file);
    return $ext[count($ext)-1];
  }

  print(getExt('http://www.sina.com.cn/abc/de/fg.html.php&#63;id=1'));

&#63;>
Copy after login

7. Methods to intercept Chinese strings without garbled characters

You can use mb_substr, but you need to make sure that php_mbstring.dll is loaded in php.ini, that is, make sure that the line "extension=php_mbstring.dll" exists and is not commented out, otherwise undefined function problems will occur.

The above commonly used algorithms for PHP interviews (recommended) are all the content shared by the editor. I hope it can give you a reference, and I hope you will support Script Home.

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