小算法:汉诺塔、冒泡法

汉诺塔:

<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>



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值