程序调用自身的编程技巧称为递归( recursion)。递归作为一种算法在程序设计语言中普遍应用。 一个过程或函数在其定义或说明中有直接或间接调用自身的一种方法,它一般把一个大型复杂的问题层层转化为一个与原问题类似的规模较小的问题来求解,递归策略只需少许的程序就可描述出解题过程所须要的屡次重复计算,大大地减小了程序的代码量。递归的能力在于用有限的语句来定义对象的无限集合。通常来讲,递归须要有边界条件、递归前进段和递归返回段。当边界条件不知足时,递归前进;当边界条件知足时,递归返回。算法
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
|
/*Name:HANOITOWER
*Description:solvethehanoitowerproblembyrecursion
*/
#include<stdio.h>
#include<stdlib.h>
/*movenplates:from-->to,
*thebuffercanbeusedifneeded*/
inthanoi(intn,charfrom,charbuffer,charto)
{
if
(n==1)
{
/*movetheNO.1platedirectly:from-->to*/
printf
(
"Moveplate#%dfrom%cto%c\n"
,n,from,to);
/*theNO.1plateismovedsoreturn*/
return0;
}
else
{
/*nplatestobemoved:from-->to,
*movethen-1platesabove:from-->buffer,
*givethistasktothenextrecursion*/
hanoi(n-1,from,to,buffer);
/*then-1platesaboveweremovedtobuffer,
*sotheNO.nplatecanbemoveddirectly*/
printf
(
"Moveplate#%dfrom%cto%c\n"
,n,from,to);
/*howeverthen-1platesarestillinbuffer,
*movethemtotheterminalposition,
*(the"from"positionhasnoplate,&canbeoneso-calledbuffer)*/
hanoi(n-1,buffer,from,to);
/*thetaskgivenisdonesoreturn*/
return0;
}
}
intmain()
{
#defineN4
/*NplatesinA,let'smovethemtoC*/
hanoi(N,
'A'
,
'B'
,
'C'
);
return0;
}
|
1
2
3
4
5
|
//pascal
procedurea;
begin
a;
end;
|
1
2
3
4
5
6
7
8
9
10
|
//pascal
procedureb;
begin
c;
end;
procedurec;
begin
b;
end;
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
|
//pascal
programfac2;
var
n:integer;
functionfac(n:integer):real;
begin
ifn=0thenfac:=1elsefac:=n*fac(n-1);
end;
begin
write(
'n='
);readln(n);
writeln(
'fac('
,n,
')='
,fac(n):6:0);
end.
|
1
2
3
4
5
6
7
8
9
10
11
12
|
//pascal
programlouti;
varn:integer;
functionf(x:integer):integer;
begin
ifx=1thenf:=1else
ifx=2thenf:=2elsef:=f(x-1)+f(x-2);
end;
begin
write(
'n='
);read(n);
writeln(
'f('
,n,
')='
,f(n))
end.
|
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
|
programkspv;
var
a:array[0..10000]oflongint;
i,n:integer;
procedurequicksort(l,r:longint);
vari,j,mid:longint;
begin
i:=l;j:=r;mid:=a[(l+r)div2];
repeat
whilea[i]<middoinc(i);
whilea[j]>middodec(j);
ifi<=jthen
begin
a[0]:=a[i];a[i]:=a[j];a[j]:=a[0];
inc(i);dec(j);
end;
untili>j;
ifi<rthenquicksort(i,r);
ifl<jthenquicksort(l,j);
end;
begin
write(
'inputdata:'
);
readln(n);
fori:=1tondoread(a[i]);
writeln;
quicksort(1,n);
write(
'outputdata:'
);
fori:=1tondowrite(a[i],
''
);
writeln;
end.
|