How to merge and sort PHP

Source: Internet
Author: User
This paper mainly introduces the implementation algorithm of PHP merge sort, that is, to divide the ordered sequence into several ordered sub-sequences, and then merge the ordered sub-sequences into the whole ordered sequence. Interested friends can come to know.

The merge (merge) Sort method combines two (or more than two) ordered tables into a new ordered table. One drawback of merge sorting is that it requires that the memory has another array of size equal to the number of data items. If the initial array fills up the entire memory, the merge sort will not work, but if there is enough space, the merge sort will be a good choice.

Suppose the sequence to be sorted:

4 3 7 9 2 8 6

First of all, the central idea of merge sorting is to combine two sequenced sequences into a sorted sequence.

The above sequence can be divided into:

4 3 7 9
And
2 8 6

These two sequences are then sorted separately: The result is:

Set to sequence A, with sequence B,

3 4 7 9
2 6 8

Combine the above two sequences into a sorted sequence:

The specific ideas for merging are:

Set the two position indicator, pointing to the position of sequence A and sequence B, respectively: The red indicator points to the position:

3 4 7 9
2 6 8

Compare the values of the elements pointed to by the two indicators, insert smaller inserts into a new array, such as sequence C, and move the corresponding indicator backward one:
The result is:

3 4 7 9
2 6 8

The formation of the sequence C: has been inserted into an element, just a small element of 2.
2

Then compare the elements pointed to by the indicator in sequence A and sequence B again: Put the small in sequence C and move the corresponding pointer, and the result is:

3 4 7 9
2 6 8
2 3

And so on, the iteration executes until an indicator in sequence A or sequence B has moved to the end of the array. For example:
After several comparisons, sequence B has moved the indicator out to the end of the sequence (after the last element).
3 4 7 9
2 6 8
2 3 4 6 7 8

Then the unused sequence, which is the rest of the sequence A is inserted in the back of sequence C, there is a 9 left, after inserting it into sequence C:

Sequence C Results:

2 3 4 5 6 7 8 9

This enables the operation of merging two ordered sequences into an ordered sequence,

Let's look at this combined PHP code:

/** * Merges two ordered arrays into an ordered array * @param $arrA, * @param $arrB, * @reutrn Array merged */function Mergearray ($arrA, $arrB) {  $a _ i = $b _i = 0;//Set two starting position markers  $a _len = count ($arrA);  $b _len = count ($arrB);  while ($a _i< $a _len && $b _i< $b _len) {    //when arrays A and array B are not out of bounds if    ($arrA [$a _i] < $arrB [$b _i]) {      $ arrc[] = $arrA [$a _i++];    } else {      $arrC [] = $arrB [$b _i++];    }  }  Determine if the elements in array A are all out of use, and insert them all into the C array if not: while  ($a _i < $a _len) {    $arrC [] = $arrA [$a _i++];  }  Determine if the elements in array B are all out of use, and insert them all into the C array if not: while  ($b _i < $b _len) {    $arrC [] = $arrB [$b _i++];  }  return $arrC;}

Through the above analysis and implementation of the program, it is not difficult to find that the time to merge the ordered sequence should be linear, that is, a maximum of N-1 times will occur, where n is the sum of all elements.

By the above description, we have implemented the process of making two sorted arrays.

At this point, you may have questions about how this is related to the whole sequence of merge orders. Or how can you get the first two sorted sub-sequences?
Below, we will describe what the merge sort is, and then see how the above merging and merging sorts are related:

You might want to think about whether we can sort the first half of the array with the second half of the array, and then merge the results of the sort, when we need to sort the array as follows.

For example: Array to sort:
4 3 7 9 2 8 6

First divided into 2 parts:

4 3 7 9
2 8 6

Consider the first and second halves as a sequence, and merge again (that is, split, sort, merge) operations
It will become:

Ago:
4 3
7 9

After:
2 8
6

Again, each self-sequence is merged and sorted again (split, sort, merge).

When there is only one element in the split sub-sequence (length 1), then the sequence does not have to be split, it is a sorted array. Then merge this sequence with other sequences, and eventually merge all of them into a complete array of sorted arrays.

Program implementation:

By the above description you should think that you can use a recursive program to implement this program:

To implement this program, you may need to address the following issues:

How to split an array:

Set two indicators, a pointer to an array begins with $left, a pointer to the last element of the array $right:
4 3 7 9 2 8 6

Then determine whether the $left is less than $right, if less than the number of elements in this sequence is greater than one, split it into two arrays, split the way is to generate an intermediate indicator $center, the value is $left + $right/2 divisible. The result is: 3, then divides $left into $center into a group, $center +1 to $right into a group:
4 3 7 9
2 8 6
Next, the recursive use of $left, $center, $center +1, $right respectively as the left and right indicators of two sequences, to operate. Know that there is an element in the array $left== $right. Then follow the combined array above:

/*** mergesort Merge Sort * is a driving function of the start recursive function * @param & $arr array to be sorted */function mergesort (& $arr) {$len = count ($arr);// Get the array length Msort ($arr, 0, $len-1);} /*** the actual implementation of the merge sort program * @param & $arr array needs to be sorted * @param $left the left subscript value of the int subsequence * @param $right the right subscript value of the int subsequence */function msort (&A MP; $arr, $left, $right) {if ($left < $right) {//description sub-sequence there are 1 extra elements, then split, sort, merge//calculate split position, length/2 to Integer $center =    Floor (($left + $right)/2);    Recursive calls are reordered to the left: Msort ($arr, $left, $center);    Recursive calls to the right are reordered again Msort ($arr, $center +1, $right);  Merge sort results Mergearray ($arr, $left, $center, $right); }}/*** merges two ordered arrays into an ordered array * @param & $arr, all elements to be sorted * @param $left, sort the start of sub-array a subscript * @param $center, sort sub-array A with the intermediate subscript of the sorted sub-array B, that is, the array  The end of a subscript * @param $right, sorting the end subscript for sub-array B (starting with $center+1) */function Mergearray (& $arr, $left, $center, $right) {//Set two starting position markers  $a _i = $left;  $b _i = $center +1; while ($a _i<= $center && $b _i<= $right) {//when arrays A and array B are not crossed if ($arr [$a _i] < $arr [$b _i]) {$temp [] = $arr [$a _i++];    } else {$temp [] = $arr [$b _i++];  }}//To determine if the elements within array A are all run out, insert all of them into the C array if not: while ($a _i <= $center) {$temp [] = $arr [$a _i++];  }//Determine if the elements in array B are all out of use, and insert them all into the C array if not: while ($b _i <= $right) {$temp [] = $arr [$b _i++];  }//$ARRC the sorted parts within the $arr: for ($i =0, $len =count ($temp), $i < $len, $i + +) {$arr [$left + $i] = $temp [$i]; }}//do some test: $arr = Array (4, 7, 6, 3, 9, 5, 8), MergeSort ($arr);p rint_r ($arr);

Note that the above code has a sorted array that uses reference passing, in order to save space.

Moreover, the way of merging arrays is also to save space to make relative modification, put all operations on the $arr to complete, reference delivery save resources.

Okay, the above code completes the merge sort, the time complexity of the merge sort is O (n*logn) efficiency or quite objective.

Furthermore, the central idea of merging the sorting algorithm is to decompose a complex problem into a similar small problem, and then decompose the small problem into smaller problems until it is decomposed into a method that can be solved immediately, and then the results of decomposition are merged together. This idea is described by an idiom called piecemeal. In computer science, there is a specialty called divide-and-conquer strategy (Division of the FA). Divide is the big problem becomes small problem, the cure is the small result merges into big result.

The divide-and-conquer strategy is the basis of many funny algorithms, and when we discuss the quick sort, we also use the divide-and-conquer strategy.

Finally, this algorithm is simple, although the algorithm achieves O (NLOGN) in time complexity. However, there is still a small problem, that is, when merging two arrays, if the total number of elements of the array is N, then we need to open up a space of the same size to save the merged data (that is, the $temp array in Mergearray), but also need to have $temp copy of the data will $arr, Therefore, some resources are wasted. Therefore, it is relatively less used in the actual sort.

Summary: The above is the entire content of this article, I hope to be able to help you learn.

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.