forked from TheAlgorithms/C
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlexicographic_permutations.c
65 lines (59 loc) · 1.63 KB
/
lexicographic_permutations.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
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 < strSize && str[k]; k++)
{
if (str[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);
if (n <= 0 || n >= 1000)
{
perror("Input number out of range: >0 and <1000\n");
return -1;
}
char *str = (char *)malloc(n * sizeof(char));
scanf("%s", str);
PrintSortedPermutations(str);
free(str);
return 0;
}