Summary of common php sorting algorithms and php sorting algorithms

Source: Internet
Author: User

Summary of common php sorting algorithms and php sorting algorithms

This article summarizes common php sorting algorithms, which have good reference value for algorithm design. I will share it with you for your reference. The details are as follows:

I. Insert sorting

Use a simple description in text, such as $ arr = array (,); To sort a group of numbers in sequence:
So, first, compare the second element of the array with the first element. If the first element is greater than the second element, the positions of the two are interchangeable. Next, take the third element of the array, compare the first element with the second one. If the third element is small, it is interchangeable. And so on. This is the insertion sorting. The time frequency is: 1 + 2 +... + (n-1) = (n ^ 2)/2. The time complexity is 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;  }?>

Ii. Select sorting

If you select the language description for sorting, you can do this, for example: $ arr = array (, 1 );

First, take the first and all the following ratios, find the smallest number, and then swap it with the first array (of course, if it is the first smallest, then there is no need to swap it ), next, take the second and subsequent comparisons to find the smallest number, and then swap it with the second number, and so on, that is, find the remaining smallest value each time. It can be obtained: for the first time, the time frequency is n. (The first is compared with the n-1 in the end. Find the minimum value and see if it is the first one. If it is not the first one, swap it, the order is 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 the subscript of the smallest element} if ($ min! = $ I) {// It is interchangeable if the subscript is not $ I. $ Tmp = $ arr [$ I]; $ arr [$ I] = $ arr [$ min]; $ arr [$ min] = $ tmp ;}} return $ arr ;}?>

Iii. Bubble Sorting

In fact, Bubble Sorting is not significantly different from the selected sorting. To the leftmost end. Solve the problem cyclically. The difference is that Bubble Sorting has a large number of switching locations, while selecting sorting is to find the subscript of the smallest element, and then directly exchange the position with the leftmost end.


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 sorting

In quick sorting, select a value $ a from the array and compare it with other elements. Values larger than $ a are placed in the array right. Otherwise, put it in the left array. Then, recursively call left right, namely, subdivide left right, and merge the array.

Php for fast sorting:

<? Phpfunction mySort ($ arr) {$ count = count ($ arr); if ($ count <2) {return $ arr ;}$ key = $ arr [0]; // select the first element as the comparison element. Optional values: $ 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 ;}?>

V. Merge Sorting

In fact, Merge Sorting is a splitting and merging idea. It has something in common with the fast sorting idea: a pile on the left, a pile on the right, and then merge. Implement recursive sorting. What is the difference? Their difference is also the essential difference in thinking. The sharding of fast sorting is to compare the size of a specific value, which is divided into left and right. That is, put a small pile into left, and put a large pile into right. Then, the small left is subdivided into left1 right1 .... Perform similar Recursion to complete sorting. That is to say, the left1 at the end of recursion is the minimum value.

Merge Sorting is to split from the left and right sides of the ry and recursively split it into the minimum granularity array of 2 or 1 before comparison and merge. The size of the comparison here is: The child left element is compared with the son's right element, and then sorted and merged into the father's left or right. Here, the last two arrays are merged until the original left and right are obtained, and the order of the entire array is not confirmed, it is still necessary to merge after the final left right comparison to complete the sorting in the true sense.

<? Phpfunction gbSort ($ arr) {if (count ($ arr) <= 1) {return $ arr ;}$ min = floor (count ($ arr)/2 ); // split the data with an intermediate number $ left = array_slice ($ arr, 0, $ min); $ right = array_slice ($ arr, $ min ); $ left = gbSort ($ left); // recursion $ right = gbSort ($ right); return get_merge ($ left, $ right ); // call the 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); // For comparison, small removal, and put in the array $ m. } Return arr_merge ($ m, $ left, $ right); // Merge (because you do not know which of the left right statements is null, merge them in a unified manner)}?>

6. Heap sorting

In this example, the fixDown function is used to adjust down a node. The default value is 1, which facilitates the calculation of parent-child node relationships.

Note:

Parent-child relationship with the Start Node 1: parent node k, child node is 2 K, 2 k + 1 child node j, parent node is floor (j/2) floor is rounded down
Parent-child relationship with the Start Node 0: parent node k, child node 2 K + 1, 2 k + 2 child node j, parent node is floor (J-1)/2)

The parameter $ k is used to adjust the vertex position, and $ lenth is the array length, that is, the coordinates from the start of 1 to the last node.

<? Phpfunction fixDown (& $ arr, $ k, $ lenth) {while (2 * $ k <= $ lenth) {// as long as the current node has a subnode, you need to continue this loop $ j = $ k * 2; if ($ j <$ lenth & $ arr [$ j] <$ arr [$ j + 1]) $ j ++; // if the child node has a right node and the right node is larger than the left node, switch to the right node. If ($ arr [$ j] <$ arr [$ k]) break; // if no parent node is large, 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 (,); headSort ($ arr);?>

I hope the Sorting Algorithm examples described in this article will be helpful for php programming.


Using Java to implement several common sorting algorithms

Various sorting methods implemented in Java, including insertion sorting, Bubble sorting, selection sorting, Shell sorting, quick sorting, Merge Sorting, heap sorting, and SortUtil.
Sort inserts: 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 <data. length; I ++ ){
For (int j = I; (j0) & (data [j] <data [J-1]); j --){
SortUtil. swap (data, j, J-1) ;}}} Bubble Sorting: 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 <data. length; I ++ ){
For (int j = data. length-1; ji; j --){

What are common sorting algorithms?

A sorting algorithm is an operation that sorts a string of records in ascending or descending order based on the size of one or more keywords.
Category
The sorting algorithms used in computer science are generally classified:
The computational complexity (worst, average, and best) is based on the size of the string column (list) (n ). Generally, good performance is O. (N log n), and the bad behavior is Ω (n2 ). The ideal performance for a sorting is O (n ). The average sum of sorting algorithms that use only one abstract key comparison operation always requires at least Ω (n log n ).
Memory usage (and use of other computer resources)
Stability: The stable Sorting Algorithm maintains the relative sequence of records based on the equal key (in other words, the value. That is, a sorting algorithm is stable, that is, when two records R and S have equal key values and R appear before S in the original string column, in the sorted string column, R will also be before S.
General Methods: insert, exchange, select, merge, and so on. The exchange sorting includes bubble sort and quicksort ). Select shaker sorting and heapsort sorting ).
When equal elements cannot be distinguished, such as integers, stability is not a problem. However, assume that the following number pairs will be sorted by their first number.
(4, 1) (3, 1) (3, 7) (5, 6)
In this case, two different results may be generated. One is to maintain the relative order based on equal key values, and the other is not:
(3, 1) (3, 7) (4, 1) (5, 6) (maintain order)
(3, 7) (3, 1) (4, 1) (5, 6) (order changed)
The unstable sorting algorithm may change the relative sequence of records in equal key values, but the stable Sorting Algorithm never does. The unstable sorting algorithm can be used as a stable algorithm in special cases. One way to do this is to manually expand the key value comparison. In other aspects, the comparison between two objects with the same key value will be determined to use the entries in the original data order, as a single finals. However, remember that this order usually involves extra space burden.
Sort the algorithm list
In this table, n is the number of records to be sorted and k is the number of different key values.
Stable
Bubble sort-O (n2)
Cocktail sorting (Cocktail sort, bidirectional bubble sorting)-O (n2)
Insertion sort-O (n2)
Bucket sort-O (n); requires O (k) Additional memory
Counting sort-O (n + k); requires O (n + k) Additional memory
Merge sort-O (n log n); requires O (n) Additional memory
Sort by in-situ merging-O (n2)
Binary tree sort-O (n log n); requires O (n) Additional memory
Pigeonhole sort-O (n + k); requires O (k) Additional memory
Base sorting (radix sort)-O (n · k); requires O (n) Additional memory
Gnome sort-O (n2)
Library sort-O (n log n) with high probability, requires (1 + ε) n additional memory
Unstable
Selection sort-O (n2)
Shell sort-O (n log n) if you use the best current version
Comb sort-O (n log n)
Heapsort-O (n log n)
... The remaining full text>

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.