PHP interview Common algorithm (recommended) _php instance

Source: Internet
Author: User

First, bubble sort

Basic idea:

Scans multiple times for arrays that need to be sorted from back forward (in reverse order), exchanging these two values when the sequence of adjacent two values is found to be inconsistent with the rules for sorting requirements. This relatively small (large) number will gradually move from the back to the front.

Bubble sort

<?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));
>

Second, fast sorting

Basic idea:

Select an element (most of the first) in the array as the ruler, scan it again. The array will precede the ruler with elements smaller than the ruler, after all elements larger than the ruler are ranked, and recursively divide each subsequence into smaller sequences until all sequence sequences are consistent.

Quick Sort

<?php
  //Quick sort
    function Quick_sort ($arr) 
    {
      //first determine whether the need to continue
      $length = count ($arr);
      if ($length <= 1) 
      {return
        $arr;
      }
    
      $base _num = $arr [0];//Select a ruler to select the first element

      //Initialize two arrays
      $left _array = Array (), or less than the ruler's
      $right _array = Array ();// For
      ($i =1 $i < $length $i + +) 
      {      ///traverse all elements except the ruler, in two arrays by size relationship
        if ($base _num > $arr [$i] 
        {
          //Put the left array
          $left _array[] = $arr [$i];
        } 
        else 
        {
          //put to the right
          $right _array[] = $arr [$i];
        }
      The same sort processing//recursive call is performed on the left and right arrays respectively
      , and the results are recorded
      $left _array = Quick_sort ($left _array);
      $right _array = Quick_sort ($right _array);
      Merges the left ruler right return
      Array_merge ($left _array, Array ($base _num), $right _array)
    ;

    $arr = Array (3,1,2);
    Var_dump (Quick_sort ($arr));

>

Three or two-point search

Basic idea:

Suppose the data is sorted in ascending order, and for the given value x, if the current position value equals X, the lookup succeeds if X is less than the current position value, is searched in the first half of the series, and if X is greater than the current position value, the search continues in the second half of the sequence until it is found. (Use when data is large)

Two-point Search

<?php
  ///two-find
  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));
? >

Four, order to find

Basic idea:

Look down from the first element of the array, and if there are elements that are consistent with the target, the lookup succeeds; if the last element still has no target element, the lookup fails.

Sequential Lookup

<?php
  //Order lookup
  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;
    }
  }
? >

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

<?php  
  function My_scandir ($dir)
  {
    $files = array ();
    if ($handle = Opendir ($dir))
    {while
      ($file = Readdir ($handle))!== false) 
      {
        if ($file!= ' ... ' && Amp $file!= '. ')
        {
          if (Is_dir ($dir.) /". $file))
          {
            $files [$file]=my_scandir ($dir.") /". $file);
          }
          else
          {
            $files [] = $file;
          }

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

  Var_dump (My_scandir) ('. /'));
? >

Six, write a function, as efficiently as possible from a standard URL to remove the file extension

<?php
  function Getext ($url)
  {
    $arr = Parse_url ($url);//parse_url resolves a URL and returns an associative array containing the various components that appear in the 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 ' )//The basename function returns the filename part of the path
    $ext = Explode ('. ', $file);
    return $ext [Count ($ext)-1];
  }

  Print (Getext (' http://www.sina.com.cn/abc/de/fg.html.php?id=1 '));

? >

Seven, the realization of Chinese character string interception without garbled method

You can use MB_SUBSTR, but you need to make sure that Php_mbstring.dll is loaded in php.ini to ensure that the "Extension=php_mbstring.dll" line exists and is not commented out, otherwise there is an issue with undefined functions.

The above PHP interview commonly used algorithm (recommended) is a small series to share all the content, hope to give you a reference, but also hope that we support the cloud-dwelling community.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.