PHP implementation of common sorting algorithm summary, PHP sorting algorithm _php tutorial

Source: Internet
Author: User

PHP implementation of common sorting algorithm summary, PHP sorting algorithm


This paper summarizes the common PHP sorting algorithm, which has a good reference value in the design of the algorithm. We are now sharing it for your reference. Specific as follows:

First, insert sort

A simple description of the text, such as $arr = Array (4,2,4,6,3,6,1,7,9); Such a set of numbers are ordered:
So, first, take the second element of the array and the first element to compare, if the first element is greater than the second element, then let the two positions swap, then, take the third element of the array, and the second, the first element, if the third element is small, then the interchange. In turn. This is the insertion sort, and its time frequency is: 1+2+...+ (n-1) = (n^2)/2. Then it has a time complexity of O (n^2).

The PHP implementation code is as follows:

<?phpfunction Insertsort ($arr) {   $count = count ($arr);   if ($count <2) {  return $arr;    }   for ($i =1; $i < $count; $i + +) {   $tmp = $arr [$i];   $j = $i-1;   while (j>=0&& $arr [$j]< $arr [$i]) {  $arr [$i] = $arr [$j];             $arr [$j] = $tmp;  $j--;   }    }    return $arr;  }? >

Second, choose the sort

Select Sort by language description, can be this, such as: $arr = Array (4,3,5,2,1);

First, take the first and all the ratios, find the smallest number, and then swap with the first array (of course, if it is the first smallest, then it is not interchangeable), then the loop, namely: Take the second and the back of the comparison, find the smallest number, and then the second number, and so on, That means finding the smallest remaining value every time. Available: The first time, the frequency is N, (the first and the back of the n-1 comparison, find the smallest, and then see is not the first, not the first word for interchange) in the future, in turn, minus one. Its time complexity is also O (n^2);

The PHP implementation code is as follows:

<?phpfunction Selectsort ($arr) {   $count = count ($arr);   if ($count <2) {  return $arr;    }   for ($i =0; $i < $count; $i + +) {   $min = $i;   For (j= $i +1; $j < $count; $j + +) {  if ($arr [$min]> $arr [$j]) {    $min = $j;//find subscript for the smallest element  }   if ($min! = $i) {//If the subscript is not $i, it is interchangeable.   $tmp = $arr [$i];               $arr [$i] = $arr [$min];    $arr [$min] = $tmp;    }    }    return $arr;  }? >

Third, bubble sort

The bubble sort is actually no different than the selection sort. is to find the smallest and put it to the left end. Loop through the problem in turn. The difference is that the number of swap locations for the bubble sort is more, and the selection sort is to find the lowest element subscript, then the direct and leftmost swap positions.


The PHP implementation code is as follows:

<?phpfunction Selectsort ($arr) {   $count = count ($arr);   if ($count <2) {  return $arr;    }   for ($i =0; $i < $count; $i + +) {for   (j= $i +1; $j < $count; $j + +) {  if ($arr [$i]> $arr [$j]) {    $tmp = $arr [$i ];               $arr [$i] = $arr [$i];    $arr [$i] = $tmp;  }   }    }    return $arr;  }? >

Iv. Quick Sort

Quick sort, in words, select a value of $ A from the array, then compare it to the rest of the elements, put it in the array right, or in the left of the array. The left right is then recursively called, namely: subdivide left right and finally merge the array.

PHP Enables quick ordering:

<?phpfunction Mysort ($arr) {   $count = count ($arr);   if ($count <2) {  return $arr;    }   $key = $arr [0];//selects the first element as the comparison element, optionally other    $left = Array ();           $right = Array ();    for ($i =1; $i < $count; $i + +) {   if ($key >= $arr [$i]) {  $left [] = $arr [$i];    } else{  $right [] = $arr [$i];    }    }    $left = Mysort ($left);    $right = Mysort ($right);    $result = Array_merge ($left, $right);    return $result;  }? >

Five, merge sort

In fact, merge sort is a kind of splitting, merging thought. And quick sort ideas have something in common, a pile on the left, a pile on the right, and then merge. Sort by recursive implementation. Where is the difference? Their difference is also the ideological essence of the difference, the rapid sorting of the split, is to select a specific value for the size comparison, thus divided into left and right. That is, small piles put in left, large piles put right. Then, the small left is subdivided into left1 right1 .... Sort by doing a similar recursive completion. In other words, the left1 at the very end of the recursion is the minimum value that has been broken down.

The merge sort, from the left and right of the geometry, has been recursively cut into 2 or 1 of the smallest array of granularity before it starts to compare size and then merge. The comparison size here is that the son left element is compared with the son's right element and then sorted into a parent left or right. In this case, until the respective sort merge completes the last two arrays: the first left and right, and only until their respective order, does not confirm the order of the entire array, or it is necessary to complete the real sort by comparing after the end of the back.

<?phpfunction Gbsort ($arr) {    if (count ($arr) <=1) {return $arr;}    $min = Floor (count ($arr)/2), or//divide the middle number    $left = array_slice ($arr, 0, $min);    $right = Array_slice ($arr, $min);    $left = Gbsort ($left); Recursive    $right = Gbsort ($right);    Return Get_merge ($left, $right);//Call sort merge function to merge}function Get_merge ($left, $right) {while    (count ($left) && Count ($right)) {        $m [] = $left [0]> $right [0]? Array_shift ($right): Array_shift ($left);        To compare, small to remove, and put into the array $m.    }    Return Arr_merge ($m, $left, $right);//merge (because you do not know which of the left is empty, so you merge it uniformly)}?>

Vi. sequencing of Heaps

In this example, the Fixdown function implements a downward adjustment to a node, where the starting node is 1, which facilitates the calculation of parent-child node relationships

Note:

Parent-child relationship with a starting node of 1: Parents K, child nodes 2K, 2k+1 child node J, parent node is floor (J/2) floor is rounded down
Parent-child relationship with starting node 0: Parents K, child node 2k+1, 2k+2 child node J, parent node floor ((j-1)/2)

The parameter $k is the position of the adjustment point, $lenth the array length, which is the coordinates from 1 to the last node.

<?phpfunction Fixdown (& $arr, $k, $lenth) {while ($k <= $lenth) {//As long as the current node has child nodes, you need to continue the loop    $j = $k *;    if ($j < $lenth && $arr [$j]< $arr [$j +1]) $j + +;  As long as the child node has the right node, and the right node is larger than the left node, switch to the right node operation. If    ($arr [$j] < $arr [$k]) break;//If the child nodes are not large, then the adjustment ends.       Exch ($arr [$j], $arr [$k]);  $k = $j;  }} Function exch (& $a, & $b) {  $tmp = $a; $a = $b; $b = $tmp;} Function Headsort (& $arr) {  $len = count ($arr);  Array_unshift ($arr, NULL);  for ($i = $len/2; $i >=1; $i-) {    Fixdown ($arr, $i, $len);  }  while ($len >1) {    exch ($arr [1], $arr [$len]);    Fixdown ($arr, 1,--$len);  }  Array_shift ($arr);} $arr = Array (4,6,4,9,2,3); Headsort ($arr);? >

It is hoped that the sorting algorithm example described in this paper will be helpful to everyone's PHP programming.


Implementation of several common sorting algorithms using Java

Insert Sort: package org.rut.util.algorithm.support;
Import org.rut.util.algorithm.sortutil;/*** @author treeroot
* @since 2006-2-2
* @version 1.0*/public class Insertsort implements sortutil.sort{
/* (non-javadoc)
* @see Org.rut.util.algorithm.sortutil.sort#sort (int[]) */public void sort (int[] data) {int temp;for (int i=1;i for (int j=i; (j0) && (Data[j] sortutil.swap (data,j,j-1);}}} Bubble sort: Package org.rut.util.algorithm.support;
Import org.rut.util.algorithm.sortutil;/*** @author treeroot
* @since 2006-2-2
* @version 1.0*/public class Bubblesort implements sortutil.sort{
/* (non-javadoc)
* @see Org.rut.util.algorithm.sortutil.sort#sort (int[]) */public void sort (int[] data) {int temp;for (int i=0;i for (int j=data.length-1;ji;j--) {
&nbs P

What are the common sorting algorithms?

Sorting algorithms so-called sort, is to make a series of records, according to the size of one or some of the keywords, increment or decrement the arrangement of operations.
Classification
The sorting algorithms used in computer science are usually categorized as:
The computational complexity (worst, average, and best performance), based on the size of the list (n). Generally speaking, good performance is O. (n log n), and the bad behavior is Ω (n2). The ideal performance for a sort is O (n). A sort algorithm that uses only one abstract key comparison operation always requires at least Ω (n log n) on average.
Memory usage (and the use of other computer resources)
Stability: The stable sorting algorithm maintains the relative order of records according to the equal key (in other words, the value). That is, a sorting algorithm is stable, that is, when there are two equal key records R and S, and in the original string column R appears before s, in the sorted string column R will also be before S.
General methods: Insert, Swap, select, merge, and so on. The interchange sort contains the bubbling sort (bubble sort) and quick sort (quicksort). Select sort contains shaker sort and heap sort (heapsort).
When equal elements are indistinguishable, such as integers, stability is not a problem. However, suppose the following pairs of numbers will be sorted by their first number.
(4, 1) (3, 1) (3, 7) (5, 6)
In this case, it is possible to produce two different results, one to maintain the relative order according to the equivalent key value, while the other one does not:
(3, 1) (3, 7) (4, 1) (5, 6) (Maintenance Order)
(3, 7) (3, 1) (4, 1) (5, 6) (the order is changed)
The unstable sorting algorithm may change the relative order of records in equal key values, but the stable sort algorithm never does. An unstable sort algorithm can be particularly time-stabilized. One way to do this is to artificially expand the comparison of the key values, so that in other respects the same key value of the comparison between the two objects, it will be decided to use in the original data order of the entries, as a same sub-finals. However, keep in mind that this order usually involves additional space burdens.
List of permutation algorithms
In this table, n is the number of records to be sorted and K is the number of different key values.
Stability of
Bubble sort (bubble sort)-O (N2)
Cocktail sort (Cocktail sort, bidirectional bubble sort)-O (N2)
Insert sort (Insertion sort)-O (N2)
Bucket sort (bucket sort)-O (n); Requires O (k) Extra memory
Count sort (counting sort)-O (n+k); Requires O (N+K) extra memory
Merging sort (merge sort)-O (n log n); Requires O (n) Extra memory
In situ merge sort-O (N2)
Binary trees sort (binary tree sort)-O (n log n); Requires O (n) Extra memory
Pigeon Nest Sort (pigeonhole sort)-O (n+k); Requires O (k) Extra memory
Radix sort (radix sort)-O (n k); Requires O (n) Extra memory
Gnome Sort-o (n2)
Library sort-o (n log n) with high probability, requires (1+ε) n Extra memory
Not stable
Select sort (Selection sort)-O (N2)
Hill sort (shell sort)-O (n log n) if using the best current version
Comb sort-o (n log n)
Heap sort (heapsort)-O (n log n)
...... Remaining full text >>

http://www.bkjia.com/PHPjc/875872.html www.bkjia.com true http://www.bkjia.com/PHPjc/875872.html techarticle PHP Implementation of common sorting algorithm summary, PHP sorting algorithm This article summarizes the common PHP sorting algorithm, in the design of the algorithm has a good reference value. We are now sharing for your information ...

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