汉诺塔:
<span style="font-size:18px;">// Hanoi.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include <iostream>
//#include <vector>
//#include <fstream>
using namespace std;
const int LEN=20;
long int count=0;
void Move(int n,char A,char B,char C)
{
if(n==1)
{
cout << n << ": " << A << "--->" << C << " count=" << count++ << endl;
}
else
{
Move(n-1,A,C,B);
cout << n << ": " << A << "--->" << C << " count=" << count++ << endl;
Move(n-1,B,A,C);
}
}
int main(void)
{
char A='A',B='B',C='C';
cout << "begin:=======================";
Move(LEN,A,B,C);
system("pause");
return 0;
}
</span>
冒泡法:
<span style="font-size:18px;">// BubbleSort.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include <iostream>
using namespace std;
const int LEN=5;
void show(int* a,int length)
{
for(int i=0;i<length;i++)
cout << *(a+i) << ' ';
cout << endl;
}
int main(void)
{
int a[LEN]={5,4,3,2,1};
show(a,LEN);
cout << endl << "==================" << endl ;
int tmp;
for(int i=1;i<=LEN-1;i++)
{
cout << "第" << i << " 趟" << endl;
for(int j=0;j<LEN-i;j++)
{
if(a[j]>a[j+1])
{
//cout << "a[" << j << "]=" << a[j] << " a[" << j+1 << "]=" << a[j+1] << endl;
tmp=a[j];
a[j]=a[j+1];
a[j+1]=tmp;
//cout << "a[" << j << "]=" << a[j] << " a[" << j+1 << "]=" << a[j+1] << endl;
}
show(a,LEN);
//cout << " i=" << i <<endl;
//cout << "第" << i << " 趟" << endl;
}
}
cout << "排序完成!" << endl;
show(a,LEN);
cout << endl;
system("pause");
return 0;
}</span>