程序調用自身的編程技巧稱爲遞歸( 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.
|