Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
C program to find permutations of given strings
In C, generating permutations of strings means finding all possible arrangements of a given array of strings. We can use the next permutation algorithm to systematically generate all permutations in lexicographical order.
Syntax
int next_permutation(int n, char **strings);
Algorithm
The next permutation algorithm works by −
- Finding the rightmost element that is smaller than its next element
- Finding the smallest element on the right side that is larger than the found element
- Swapping these two elements
- Reversing the sequence after the original smaller element
Example
Let us see the following implementation to generate all permutations of given strings −
#include <stdio.h>
#include <string.h>
int next_permutation(int n, char **s) {
for (int i = n - 1; i > 0; i--) {
if (strcmp(s[i], s[i - 1]) > 0) {
int j = i + 1;
for (; j < n; j++) {
if (strcmp(s[j], s[i - 1]) <= 0)
break;
}
char *t = s[i - 1];
s[i - 1] = s[j - 1];
s[j - 1] = t;
for (; i < n - 1; i++, n--) {
t = s[i];
s[i] = s[n - 1];
s[n - 1] = t;
}
return 1;
}
}
for (int i = 0; i < n - 1; i++, n--) {
char *t = s[i];
s[i] = s[n - 1];
s[n - 1] = t;
}
return 0;
}
int main() {
char *strings[] = {"abc", "def", "ghi"};
int n = 3;
do {
for (int i = 0; i < n; i++) {
printf("%s%c", strings[i], i == n - 1 ? '<br>' : ' ');
}
} while (next_permutation(n, strings));
return 0;
}
Output
abc def ghi abc ghi def def abc ghi def ghi abc ghi abc def ghi def abc
How It Works
The algorithm generates permutations in lexicographical order by −
- Step 1: Start with the given arrangement of strings
- Step 2: Find the next lexicographically greater permutation
- Step 3: Continue until no more permutations exist
- Step 4: The function returns 0 when all permutations are exhausted
Key Points
- The algorithm uses
strcmp()to compare strings lexicographically - Time complexity is O(n! × n) where n is the number of strings
- The function modifies the original array in place
- Returns 1 if next permutation exists, 0 otherwise
Conclusion
The next permutation algorithm efficiently generates all permutations of strings in lexicographical order. This approach is useful when you need to systematically explore all possible arrangements of string elements.
Advertisements
