成果展示

实现原理
- 迭代参数设计:源char[] src,展示数据char[] show
- 迭代结束条件:当src size=1,将show和src[0]组合打印
- 迭代过程:每次将src取出一个char,放到show,组合成nextShow;
将src剩余数据组合成nextSrc;从而让迭代继续
源码展示
#define _CRT_SECURE_NO_WARNINGS
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#ifndef SORT_NUM
#define SORT_NUM 100
#endif
static int num = 0;
static char data[SORT_NUM];
static void runSort(char *src, char *show) {
if (show != NULL) {
num++;
printf("排列组合第%d次:%s\n",num,show);
}
int size =0;
for (size; src[size] != '\0'; size++) {}
if (size == 1) {
num++;
char buffer[SORT_NUM];
if (show != NULL) {
sprintf(buffer, "%s%c", show, src[0]);
}
else {
sprintf(buffer, "%c",src[0]);
}
printf("排列组合第%d次:%s\n", num, buffer);
}
else {
for (int i = 0; i < size; i++) {
char nextShow[SORT_NUM];
if (show != NULL) {
sprintf(nextShow, "%s%c", show, src[i]);
}
else {
sprintf(nextShow, "%c", src[i]);
}
char nextSrc[SORT_NUM];
_Bool flag = 0;
for (int j = 0; j < size; j++) {
if (j == i) {
flag = 1;
}
else {
if (flag) {
nextSrc[j - 1] = src[j];
}
else {
nextSrc[j] = src[j];
}
}
}
nextSrc[size-1] = 0;
runSort(nextSrc, nextShow);
}
}
}
static void getData() {
printf("请输入%d以内要排列组合的字符\n", SORT_NUM);
char p[SORT_NUM];
scanf("%s", p);
printf("\n输入的排列组合为%s\n", p);
int index = 0;
for (int i = 0; p[i] != '\0'; i++) {
_Bool flag = 0;
for (int j = 0; j < index; j++) {
if (data[j] == p[i]) {
flag = 1;
break;
}
}
if (!flag) {
data[index] = p[i];
index++;
}
}
data[index] = 0;
printf("开始排列组合为%s\n", data);
}
void sort() {
num = 0;
getData();
runSort(data,NULL);
printf("是否要重新开始yes or no\n");
char yes[] = "yes\0";
char p[SORT_NUM];
scanf("%s", p);
if (strcmp(yes, p)==0) {
sort();
}
else {
printf("\n输入的是%s\n", p);
}
}
main代码
#include<stdio.h>
#include"sort.h"
#pragma comment(lib,"sort")
void main() {
sort();
getchar();
}
总结
c语言的基础还是很重要的,处理char io的语法弄得很麻烦!成功了还是很开心的