Non-repeated string Sorting Algorithm

Source: Internet
Author: User
[Description]

Enter a string to print all characters in the string.

For example, if the input string ABC is used, all strings that can be sorted by characters A, B, and C are output.

ABC, ACB, Bac, BCA, cab, and CBA.

[Analysis]

Select each element from the set, and use it as the first element in the arrangement. Then, the remaining elements are arranged in full order. In this way, all elements are arranged recursively. Taking ABC as an example, we can do this: Take ABC as an example.

  • Fix a and find the following BC: ABC, ACB. After the request is completed, a and B exchange to obtain the BAC.
  • Fix B and locate the following AC: BAC and BCA. After the request is completed, place C in the first position to obtain the CBA.
  • Fix C and find the order of the following BA: CBA and cab.
[Code]

<pre name="code" class="cpp">#include <stdio.h>#include <stdlib.h>#include <string.h>void swap(char *str, int begin, int k){char tmp;tmp = *(str + begin);*(str + begin) = *(str + k);*(str + k) = tmp;}int is_swap(char *str, int begin, int k){int i;for (i = begin; i < k; i ++)if(*(str + i) == *(str + k))return 0;return 1;}void permutation(char *str, int begin, int end){int k;if (begin == (end - 1)) {printf("%s\n", str);return;}for (k = begin; k < end; k++)if(is_swap(str, begin, k)) {swap(str, begin, k);permutation(str, begin + 1, end);swap(str, begin, k);}}int main(void){char str[10];int length;gets(str);length = strlen(str);printf("%d\n", length);permutation(str, 0, length);return 0;}

 

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.