10 full sorting of STL series (Baidu Xunlei pen exam)

Source: Internet
Author: User

Full sorting is a hot topic in the test interview, because it is difficult to evaluate Recursive Implementation and non-Recursive Implementation, so as to distinguish the examinee's level. Therefore, Baidu and Xunlei have both taken the test in campus recruitment and the examination of programmers and software designers. Therefore, this article summarizes the full arrangement to help you better learn and understand. You are welcome to point out any supplement to this article.

First, let's take a look at how the question is required (Baidu Xunlei's strokes ).

Write a function in C ++, such as Foo (const char * Str), and print out the full arrangement of Str,
Such as ABC, ACB, BCA, DAC, cab, and CBA.

 

1. Recursive Implementation of full Arrangement

For convenience, use 123 as an example. 123 is arranged in the ascending order of 123, 132, 213, 231, 312, and 321. First, consider how the number 213 and 321 is obtained. Obviously, both of them are obtained from the exchange between 1 in 123 and the next two numbers. Then, we can exchange the second number of 123 and the third number to get 132. Similarly, 213 and 321 can be obtained based on 231 and 312. So you can know --The full arrangement is to switch each number from the first number to the number next to it.After finding this rule, recursive code is easily written:

// Recursive Implementation of full sorting # include <stdio. h> # include <string. h> void swap (char * a, char * B) {char T = * A; * A = * B; * B = T ;} // K indicates the number selected, and M indicates the number of the selected number. void allrange (char * pszstr, int K, int m) {If (k = m) {static int s_ I = 1; printf ("% 3d arrange \ t % s \ n", s_ I ++, pszstr);} else {for (INT I = K; I <= m; I ++) // switch the number of I to the number next to it to get a new arrangement {swap (pszstr + k, pszstr + I); allrange (pszstr, k + 1, m); swap (pszstr + k, pszstr + I) ;}} void Foo (char * pszstr) {allrange (pszstr, 0, strlen (pszstr) -1);} int main () {printf ("Fully-arranged Recursive Implementation \ n"); printf ("-- by morewindows (http://blog.csdn.net/MoreWindows) -- \ n "); char sztextstr [] = "123"; printf ("% s in full order: \ n", sztextstr); Foo (sztextstr); Return 0 ;}

The running result is as follows:

Note that this method does not take into account repeated numbers. For example, 122 will output:

This output absolutely does not meet the requirements. Therefore, we need to remove the repeated series.

 

2. Remove repeated full-permutation recursion implementations

BecauseThe full arrangement is to switch each number from the first number to the number next to it.Let's first try to add such a judgment -- if a number is the same as the number next to it, the two numbers will not be exchanged. For example, if the number is 122, the first number is exchanged with 212 and 221. Then the second number in 122 does not need to be exchanged with the third number, but for 212, the second number is different from the third number, and 221 is obtained after the exchange. It is the same as 122 that is obtained from the exchange of the first number and the third number in 221. This method does not work.

New ThinkingFor 122, the first number 1 is exchanged with the second number 2 to get 212, and then the first number 1 is exchanged with the third number 2, because the third number is equal to the second number, therefore, the first number is no longer exchanged with the third number. Consider another 212, and the second number can be exchanged with the third number to solve 221. In this case, the full order is generated.

In this way, we also get the rule to remove duplicates in the entire arrangement --The fully arranged deduplication refers to the exchange of each number from the first number with a non-repeated number next to it.In programming, when the number of I is exchanged with the number of J, it is required that [I, j) do not have a number equal to the number of J. The complete code is provided below:

// Recursive Implementation of deduplicated sorting # include <stdio. h> # include <string. h> void swap (char * a, char * B) {char T = * A; * A = * B; * B = T;} // In the pszstr array, whether there are numbers in [nbegin, nend) that are equal to the numbers whose subscript is nend bool isswap (char * pszstr, int nbegin, int nend) {for (INT I = nbegin; I <nend; I ++) if (pszstr [I] = pszstr [nend]) return false; return true;} // K indicates the number of the selected number, M indicates a few. void allrange (char * pszstr, int K, int m) {If (k = m) {static int s_ I = 1; printf ("% 3d arrange \ t % s \ n", s_ I ++, pszstr);} else {for (INT I = K; I <= m; I ++) // switch the number of I to the number next to it to get a new arrangement {If (isswap (pszstr, K, I )) {swap (pszstr + k, pszstr + I); allrange (pszstr, k + 1, m); swap (pszstr + k, pszstr + I );}}}} void Foo (char * pszstr) {allrange (pszstr, 0, strlen (pszstr)-1);} int main () {printf ("Recursive Implementation of deduplicated permutation \ n"); printf ("-- by morewindows (http://blog.csdn.net/MoreWindows) -- \ n "); char sztextstr [] = "122"; printf ("% s in full order: \ n", sztextstr); Foo (sztextstr); Return 0 ;}

The running result is as follows:

 

Okay, now we are familiar with writing recursive methods, and considering the possible repeated series problems caused by repeated data in strings. So how can we use non-recursive methods to get a full arrangement?

 

3. Non-Recursive Implementation of full Arrangement

We need to consider non-recursive implementations of Full Permutation. First, we need to consider how to calculate the next permutation of strings. For example, the next sorting of "1234" is "1243 ". As long as you repeatedly find the next arrangement of the string, the full arrangement will be solved.

How do I calculate the next permutation of strings? To consider the string "926520", we will find the increasing numbers adjacent to the first pair from the back and forth. "20" and "52" are not incrementing. "26" meets the requirements, the first digit 2 is the replacement number, and the subscript of the replacement number is called the replacement point. Then, find a minimum number that is larger than the replacement number (This number must exist ), 0 and 2 won't work. 5 can. Exchange 5 and 2 to get "956220", and then reverse the string "6220" after the replacement point to get "950226 ".

For sorting like "4321", which is already the largest, use the processing method in STL to reverse the entire string to get the sorting of the smallest "1234" and return false.

In this way, as long as a loop is added with the function of calculating the next permutation of strings, a non-recursive full permutation algorithm can be easily implemented. Based on the above ideas and the implementation source code in STL, it is not difficult to write a high quality code. It is worth noting that you can write the code for fast sorting by yourself before sorting strings (see "quick sorting of the six typical vernacular algorithms"). you can also directly use the quick sorting function in the VC Library (see quick sorting function in the VC library function). The complete code is listed below:

// Non-Recursive Implementation of full sorting # include <stdio. h> # include <stdlib. h> # include <string. h> void swap (char * a, char * B) {char T = * A; * A = * B; * B = T ;} // reverse interval void reverse (char * a, char * B) {While (A <B) Swap (A ++, B --);} // The next bool next_permutation (char a []) {char * pend = a + strlen (a); if (a = pend) return false; char * P, * q, * pfind; pend --; P = pend; while (P! = A) {q = P; -- p; If (* P <* q) // returns the number of adjacent 2 numbers in descending order, the previous number is the replacement number {// The first number pfind = pend, which is greater than the replacement point from the back to the front. While (* pfind <= * p) -- pfind; // replace swap (pfind, P); // all the numbers after the replace point reverse (Q, pend); Return true ;}} reverse (p, pend ); // if there is no next arrangement, return truereturn false after all reversal;} int qsortcmp (const void * pA, const void * pb) {return * (char *) pa-* (char *) Pb;} int main () {printf ("fully arranged non-recursive implementations \ n"); printf ("-- by morewindows (http://blog.csdn.net/MoreWindows) -- \ n "); char sztextstr [] =" ABC "; printf (" % s in full order: \ n ", sztextstr ); // Add the sorted qsort (sztextstr, strlen (sztextstr), sizeof (sztextstr [0]), qsortcmp); int I = 1; do {printf ("% 3d arrangement \ t % s \ n", I ++, sztextstr);} while (next_permutation (sztextstr); Return 0 ;}

The test result is as follows:

Changing the string to "CBA" will output:

 

Now we have used recursive and non-recursive methods to solve the full arrangement problem. The following is a summary:

1.The full arrangement is to switch each number from the first number to the number next to it.

2.The fully arranged deduplication refers to the exchange of each number from the first number with a non-repeated number next to it.

3.The non-recursion of the full arrangement is to find the replacement number and the replacement point from the back to the front, and then find the first number larger than the replacement number to exchange with the replacement number, finally, all data after the point is replaced upside down.

 

Reprinted please indicate the source, original address: http://blog.csdn.net/morewindows/article/details/7370155

If this article is helpful to you, click "TOP" to support it. Your support is the greatest motivation for my writing. Thank you.

 

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.