‘壹’ c语言遍历数组
因为数组是从0开始算起的
所以a[2][3]数起来是
第0行和第1行
第0列,第1列,第2列
i表示的是行,当初始化i=0时表示的是第0行,当i++之后,i=1时表示的是第1行,已经表示完数组的行数了,当i=2时已经数组越界了~所以i〈2这里和〈=1效果是一样的
同理
可解释j
‘贰’ C语言:用递归的方式对数组排序
#include<stdio.h>
#defineN8
voidselection_sort(inta[],intn){
inti,t,imax=0;
if(n<1)return;
for(i=1;i<n;++i){
if(a[imax]<a[i])
imax=i;
}
if(imax!=n-1){
t=a[n-1];
a[n-1]=a[imax];
a[imax]=t;
}
selection_sort(a,n-1);
}
intmain(void){
inti,a[N]={8,5,4,6,1,2,3,7};
printf("排序前: ");
for(i=0;i<N;i++)
printf("%d",a[i]);
printf(" ");
selection_sort(a,N);
printf("排序后: ");
for(i=0;i<N;i++)
printf("%d",a[i]);
printf(" ");
return0;
}
‘叁’ c语言数组递归
递归过程中每次调用函数时形参p对应的实参都不同
‘肆’ C语言遍历字符串数组
针对每个字符遍历就可以,如果大字符串长度n、固定长度为m,那么循环为:
for (i=0;i<n-m;i++)
{
....
}
‘伍’ C语言中,递归先序遍历和非递归先序遍历的有何区别各自优缺点
1、递归就是函数调用函数本身,运行起来就是函数嵌套函数,层层嵌套,所以函数调用、参数堆栈都是不小的开销,但是程序简单。
2、非递归就是不断地对参数入栈、出栈,省去了函数层层展开、层层调用的开销。虽然参数出入栈次数多了,但是一般都开辟固定的足够大的内存来一次性开辟、重复使用。
3、非递归是从堆栈的角度来编写程序,速度快,但代码复杂。
递归是从问题本身的逻辑角度来编写,虽然速度相对慢,但代码容易理解。
如果对速度要求不高,建议用递归方式。
4、摘录例子如下:
#include <stdio.h>
#include <stdlib.h>
typedef struct BiTNode
{
char data;
struct BiTNode *lchild,*rchild;
} BiTNode,*BiTree;//二叉树的节点类型
typedef struct QNode
{
BiTNode data;
struct QNode *next;
} QNode,*QueuePtr;//队列节点类型
typedef struct
{
QueuePtr front;
QueuePtr rear;
}LinkQueue;//队列的头尾指针
void InitQueue(LinkQueue *Q)//创建队列
{
Q->front=Q->rear=(QueuePtr)malloc(sizeof(QNode));
Q->rear->next=NULL;
}
void EnQueue(LinkQueue *Q,BiTNode e)//入队操作
{
QueuePtr p;
p=(QueuePtr)malloc(sizeof(QNode));
p->data=e;
p->next=NULL;
Q->rear->next=p;
Q->rear=p;
}
BiTNode DeQueue(LinkQueue *Q)//出对操作
{
BiTNode e;QueuePtr p;
p=Q->front->next;
e=p->data;
Q->front->next=p->next;
if(Q->rear==p)
Q->rear=Q->front;
free(p);
return (e);
}
int QueueEmpty(LinkQueue *Q)//判断队列是否为空
{
if(Q->front==Q->rear )
return 1;
else
return 0;
}
BiTree CreateBiTree()//创建二叉树
{
char p;BiTree T;
scanf("%c",&p);
if(p==' ')
T=NULL;
else
{
T=(BiTNode *)malloc(sizeof(BiTNode));
T->data=p;
T->lchild=CreateBiTree(T->lchild);
T->rchild=CreateBiTree(T->rchild);
}
return (T);
}
void PreOrder(BiTree T)//先序
{
if(T!=NULL)
{
printf("%c",T->data);
PreOrder(T->lchild);
PreOrder(T->rchild);
}
}
void LevelOrder(BiTree T)//层次遍历
{
LinkQueue Q; BiTNode p;
InitQueue(&Q);
EnQueue(&Q,*T);
while(!QueueEmpty(&Q))
{
p = DeQueue(&Q);
printf("%c",p.data);
if(p.lchild!=NULL)
EnQueue(&Q,*(p.lchild));
if(p.rchild!=NULL)
EnQueue(&Q,*(p.rchild));
}
}
void main()
{
BiTree Ta;
Ta=CreateBiTree();
printf("层次遍历:");
printf("\n");
LevelOrder(Ta);
printf("\n");
printf("先序遍历:");
printf("\n");
PreOrder(Ta);
}
层次使用非递归的,用到队列
先序是用递归的
创建树使用先序递归建树
输入个例子:
abc**de*f**g***(注意*代表空格,因为空格你看不到就不好表示).