: This article mainly introduces how to merge two ordered arrays. For more information about PHP tutorials, see. Question: There are two sorted arrays A and B. The remaining space of array A is enough to accommodate B. please implement A function, insert all numbers in B into A and all numbers are sorted.
Many people start with the idea of simple insertion, which is violent enough to traverse from start to end in A. find the right position and move all the elements behind it, so that A single bit can fill the number of new inserts, this approach is the most efficient.
The other way is to compare the numbers in A and B from the end and copy the larger numbers to the end of.
This solution can also be used to replace strings. if you want to replace spaces in strings with "% 20" (in network programming, if the URL contains special characters such as spaces and "#", the parsing may fail on the server side. Therefore, the conversion is required, the conversion rule is to add two hexadecimal notation of the ASCII code after '%. For example, if the ASCII code of a space is 32, the hexadecimal value is 20, which is converted to % 20 .), If the string is inserted during traversal from start to end, a large number of times will be moved. if you know the number of spaces from the beginning, apply for more memory for the string, and then start copying from the end, replace the space to reduce the number of moves.
The code for array merging is as follows:
0 & $ num2> 0) {if ($ data1 [$ num1-1]> $ data2 [$ num2-1]) {$ data1 [$ total-1] = $ data1 [$ num1-1]; $ total --; $ num1 --;} else {$ data1 [$ total-1] = $ data2 [$ num2-1]; $ total --; $ num2 -- ;}} if ($ num2> 0) {while ($ total> 0 & $ num2> 0) {$ data1 [$ total-1] = $ data2 [$ num2-1]; $ total --; $ num2 -- ;}}$ a = array (, 9, 0,); $ B = array (, 10); merge ($, $ B, 5); print_r ($ );
Copyright Disclaimer: This article is an original article by the blogger and cannot be reproduced without the permission of the blogger.
The above introduces the merging of two ordered arrays, including the content, and hope to be helpful to friends who are interested in the PHP Tutorial.