PHP Common sorting algorithm and binary search, PHP algorithm dichotomy _php Tutorial

Source: Internet
Author: User

PHP Common sorting algorithm and binary search method, PHP algorithm dichotomy


One: Merge sort

The two ordered series are combined into an ordered series, which we call " merging ".
Merge sort is the use of merging ideas to sort the sequence. Depending on the implementation, the merge sort consists of 2 ways of " top down " and " bottom up ".


1. sort from bottom to top : Divide the number of columns to be sorted into several sub-series of length 1, then merge the series 22, obtain several ordered series with 2 length, then merge the series 22, get several ordered series with 4 length, and then merge them 22 , directly merged into a sequence. So we get the sort results we want.

2. sort from top to bottom: it is in the opposite direction from "top down" in the sort. It basically consists of 3 steps:
① decomposition-divides the current interval into a split-point mid = (low + high)/2;
② Solution--recursively merges two sub-intervals a[low...mid] and A[mid+1...high] into a sort. The end condition of recursion is that the sub-interval length is 1.
③ Merge--the sorted two sub-intervals a[low...mid] and A[mid+1...high] are merged into an ordered interval A[low...high].

    /** Merge Sort implementation process * @param array $arr array of intervals to be sorted * @param int $start The starting position of the first interval array * @param int $mid First interval The end position of the array, the start position of the second interval array * @param Int $end The end position of the second interval array * @return void*/    functionMergeArray&$arr,$start,$mid,$end)    {        $i=$start; $j=$mid+ 1; $k= 0;  while($i<=$mid&&$j<=$end)        {            if($arr[$i] <=$arr[$j])//determine the size of the respective data for the two interval arrays, and categorize                $tmp[$k++] =$arr[$i++]; Else                $tmp[$k++] =$arr[$j++]; }         while($i<=$mid)//prevents the first interval from having one data not categorized            $tmp[$k++] =$arr[$i++];  while($j<=$end)//prevent the second interval from having one data not categorized            $tmp[$k++] =$arr[$j++]; //The sorted elements are all integrated into the array arr.          for($i= 0;$i<$k; ++$i)            $arr[$start+$i] =$tmp[$i]; }    /** Merge sort (from top down) * @param array $arr arrays to be sorted * @param int $start array start position * @param int end Array End position * @return void*/    functionMerge_sort (Array&$arr,$start=0,$end=0)    {        $len=Count($arr); if($len<= 1 | |$start>=$end)            return $arr; $mid=intval(($start+$end)/2);//inter-partitionMerge_sort ($arr,$start,$mid); Merge_sort ($arr,$mid+1,$end); Merge ($arr,$start,$mid,$end); }

From the bottom up, it's just the opposite.

Two: Quick sort

By sorting the sorted data into separate two parts, one part of all data is smaller than the other part of the data, and then the two parts of the data are quickly sorted by this method, the entire sorting process can be recursive, so as to achieve the entire data into an ordered sequence. The fast-sorting body algorithm has a time operation of approximately O (log2n), and the calculated amount of the molecular area function is approximately o (n), so the total time complexity is O (nlog2n), which is obviously better than the Bubble sort O (N2). But the advantage of the algorithm is not absolute. Test analysis, when the original file keyword ordered, fast sorting time complexity is O (N2), in this case fast sorting unpleasant. And the bubble sort of this situation is O (n), but soon. Fast sorting is considered to be the best sort of sorting method in which the original file records the keyword unordered.

    /** * Quick sort * @param array $arr arrays to be sorted * @return array sorted by array*/    functionQuick_sort (Array $arr)    {        $len=Count($arr); if($len<= 1)            return $arr; $tmp=$arr[0]; $left _arr= []; $right _arr= [];  for($i= 1;$i<$len; ++$i)        {            if($arr[$i] <=$tmp)                $left _arr[] =$arr[$i]; Else                $right _arr[] =$arr[$i]; }        //Recursive classification        $left _arr= Quick_sort ($left _arr); $right _arr= Quick_sort ($right _arr); return Array_merge($left _arr,Array($tmp),$right _arr); }    

Three: Bubble sort

22 compares the size of the data element to be sorted, and finds that two data elements are exchanged in reverse order until there are no reversed data elements. The time complexity of the algorithm is O (N2). However, when the original keyword sequence is ordered, only one trip to the comparison ends, at which time the complexity is O (n).

    /** * Bubble sort * @param array $arr arrays to be sorted * @return array sorted by array*/    functionBubble_sort (Array $arr)    {        $len=Count($arr);  for($i= 0;$i<$len; ++$i)        {             for($j=$len-1;$j>$i; --$j)            {                if($arr[$j] <$arr[$j-1])                {                    $tmp=$arr[$j]; $arr[$j] =$arr[$j-1]; $arr[$j-1] =$tmp; }            }        }        return $arr; }

IV: Insert Sort

Each time a data element to be sorted is inserted into a sequential sequence, the sequence remains orderly, knowing that the data elements to be sorted are all inserted. If the goal is to arrange the sequence of n elements in ascending order, then the insertion sort is the best and worst case scenario. The best case is that the sequence is already in ascending order, in which case the comparison operation needs to be done (n-1). The worst case scenario is that the sequence is sorted in descending order, then there is a total of n (n-1)/2 times to be performed at this point. The assignment operation to insert a sort is the number of times the comparison operation is added (n-1). On average, the time complexity of inserting the sorting algorithm is O (n^2). Thus, the insertion sort is not suitable for applications with a large amount of data for sorting. However, if the amount of data that needs to be sorted is small, for example, if the magnitude is less than thousand, then inserting the sort is a good choice.

    /** Insert Sort * @param array $arr arrays to be sorted * @return array sorted by array*/    functionInsert_sort (Array $arr)    {        $len=Count($arr);  for($i= 1;$i<$len; ++$i)        {            $tmp=$arr[$i]; $j=$i-1; //insert data into the appropriate position (swap position)             while($j>= 0 &&$arr[$j] >$tmp)            {                $arr[$j+1] =$arr[$j]; $arr[$j] =$tmp; --$j; }        }        return $arr; }

Five: Select sort

Each trip selects the smallest (or largest) element from the data element to be sorted, placed in the final order of the ordered sequence, until all the data elements are sorted out. Time complexity O (N2), unstable sequencing, suitable for smaller scale

    /** Select sort * @param array $arr arrays to be sorted * @return array sorted by array*/    functionSelect_sort (Array $arr)    {        $len=Count($arr);  for($i= 0;$i<$len; ++$i)        {            $k=$i;//Mark Current Index             for($j=$i+ 1;$j<$len; ++$j)            {                if($arr[$j] <$arr[$k])                    $k=$j;//gets the current minimum value index                if($k!=$i)//if the minimum worth of indexes changes                {                    $tmp=$arr[$i]; $arr[$i] =$arr[$k]; $arr[$k] =$tmp; }            }        }        return $arr; }

6:2 points Find

    /** Binary search * @param array $arr arrays to find * @param int $key keyword to find * @return int*/    functionBin_search (Array $arr,$key)    {        $high=Count($arr); if($high<= 0)            return0; $low= 0;  while($low<=$high)        {                 //Current Find interval arr[low: High] non-empty              $mid=intval(($low+$high)/2); if($arr[$mid] ==$key)                 return $mid;//Find successful return            if($arr[$mid] >$key)                $high=$mid-1;//continue in Arr[low. Find in Mid-1]            Else                $low=$mid+ 1;//continue to find in Arr[mid+1..high]        }        return0;//when Low>high indicates that the lookup interval is empty, the lookup fails    }    $arr=Array(1,2,4,6,10,40,50,80,100,110); EchoBin_search ($arr, 80);

http://www.bkjia.com/PHPjc/1117674.html www.bkjia.com true http://www.bkjia.com/PHPjc/1117674.html techarticle php commonly used sorting algorithm and binary search, PHP algorithm dichotomy one: Merge sort two ordered series into an ordered series, we call it "merge". Merge sort ...

  • 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.