用c语言写字典序排列代码
时间: 2024-01-29 09:04:33 浏览: 20
以下是使用C语言编写的字典序排列代码:
```c
#include <stdio.h>
#include <string.h>
void swap(char *a, char *b) {
char temp = *a;
*a = *b;
*b = temp;
}
void permute(char *str, int l, int r) {
if (l == r) {
printf("%s\n", str);
} else {
for (int i = l; i <= r; i++) {
swap((str + l), (str + i));
permute(str, l + 1, r);
swap((str + l), (str + i)); // backtrack
}
}
}
int main() {
char str[100];
printf("Enter a string: ");
scanf("%s", str);
int n = strlen(str);
printf("The permutations of the string are:\n");
permute(str, 0, n - 1);
return 0;
}
```
该代码使用递归函数生成给定字符串的所有排列,并按照字典序输出。其中,`swap`函数用于交换两个字符的位置,`permute`函数用于生成字符串的所有排列。在`main`函数中,用户输入一个字符串,然后调用`permute`函数生成所有排列并输出。