gpt/2025-12-10/sorting_letters_heaps.c (view raw)
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 |
#include <stdio.h>
#define N 10
void print_perm(const char *a, int n) {
for (int i = 0; i < n; i++) {
putchar(a[i]);
}
putchar('\n');
}
// Heap's algorithm (iterative form)
void heap_permutations(char *a, int n) {
int c[N] = {0}; // counters array
print_perm(a, n);
int i = 0;
while (i < n) {
if (c[i] < i) {
// if i is even, swap a[0] and a[i]
// else swap a[c[i]] and a[i]
int swap_idx = (i % 2 == 0) ? 0 : c[i];
char tmp = a[swap_idx];
a[swap_idx] = a[i];
a[i] = tmp;
print_perm(a, n);
c[i] += 1;
i = 0;
} else {
c[i] = 0;
i++;
}
}
}
int main(void) {
char a[N] = {'a','b','c','d','e','f','g','h','i','j'};
heap_permutations(a, N);
return 0;
}
|