From 8d29a26105564f344ef3990cced8708311758fff Mon Sep 17 00:00:00 2001 From: agnimish <31532652+agnimish@users.noreply.github.com> Date: Mon, 19 Mar 2018 23:09:14 +0530 Subject: [PATCH] Create lexicographicPermutations.c Program to print all possible Permutations of a string in Lexicographical order. --- misc/lexicographicPermutations.c | 53 ++++++++++++++++++++++++++++++++ 1 file changed, 53 insertions(+) create mode 100644 misc/lexicographicPermutations.c diff --git a/misc/lexicographicPermutations.c b/misc/lexicographicPermutations.c new file mode 100644 index 00000000..cfffdbdf --- /dev/null +++ b/misc/lexicographicPermutations.c @@ -0,0 +1,53 @@ +#include +#include +#include + +void swap(char* left, char* right){ + char temp = *left; + *left = *right; + *right = temp; +} + +int compare (const void * a, const void * b){ + return ( *(char*)a - *(char*)b ); +} + +void PrintSortedPermutations(char str[]) +{ + int strSize = strlen(str); + qsort(str, strSize, sizeof(char), compare); + + int largerPermFound = 1; + do{ + // 1. Print permutation + printf("%s\n", str); + // 2. Find rightmost char that is smaller than char to its right + int i; + for (i = strSize - 2; i >= 0 && str[i] >= str[i+1]; --i){} + + // if we couldn't find one, we're finished, else we can swap + if (i >= 0){ + // 3. find character at index j such that str[j] = min(str[k]) && str[k] > str[i] for all k > i + int j = i+1, k; + for(k=j; k str[i] && str[k] < str[j]) + j = k; + } + // 3. Swap chars at i and j + swap(&str[i], &str[j]); + // 4. Sort string to the right of i + qsort(str+i+1, strSize-i-1, sizeof(char), compare); + } + else largerPermFound = 0; + } + while(largerPermFound); +} + +int main() { + int n; //size of string + scanf("%d\n",&n); + char str[n]; + scanf("%s",str); + PrintSortedPermutations(str); + return 0; +}