Created
June 14, 2015 18:25
-
-
Save AnimeshShaw/d773479f144ea5e7bb98 to your computer and use it in GitHub Desktop.
String Permutation Lexicographically in C
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #include<stdio.h> | |
| #include<stdlib.h> | |
| #include<string.h> | |
| /* Following function is used by the library qsort() function to sort an array of chars */ | |
| int compare (const void * a, const void * b); | |
| /* this function recursively prints all repeated permutations of the given string.*/ | |
| void LRecurse (char *str, char* data, int last, int index) | |
| { | |
| int i, len = strlen(str); | |
| // One by one fix all characters at the given index and recur for the subsequent indexes | |
| for ( i=0; i<len; i++ ) | |
| { | |
| // Fix the ith character at index and if this is not the last index then recursively call for higher indexes | |
| data[index] = str[i] ; | |
| // If this is the last index then print the string stored in data | |
| if (index == last) | |
| printf("%s\n", data); | |
| else | |
| LRecurse (str, data, last, index+1); | |
| } | |
| } | |
| /* This function sorts input string, allocate memory and calls LRecurse() for printing all permutations */ | |
| void LSort(char *str) | |
| { | |
| int len = strlen (str) ; | |
| char *data = (char *) malloc (sizeof(char) * (len + 1)) ; | |
| data[len] = '\0'; | |
| // Sort the input string so that we get all output strings in lexicographically sorted order | |
| qsort(str, len, sizeof(char), compare); | |
| LRecurse (str, data, len-1, 0); | |
| free(data);// Free data to avoid memory leak | |
| } | |
| // Needed for library function qsort() | |
| int compare (const void * a, const void * b) | |
| { | |
| return ( *(char *)a - *(char *)b ); | |
| } | |
| int main() | |
| { | |
| char str[] = "GOD"; | |
| printf("All permutations of %s in Lexicographic order are : \n", str); | |
| LSort(str); | |
| getchar(); | |
| return 0; | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment