C++ 策略模式调用不同的排序算法

前些天学过策略模式,最近重温了几种常用的简单排序算法,想到了策略模式,就实际操练一下。存在的问题是当存在参数数量不同时,怎么调用(如merge sort)
Sort.h(实际上为了封闭基类,可以给每个子类新建一个文件,这里为了简便就不拆分了)

#pragma once
#include<iostream>
using namespace std;
class Sort
{
public:
	virtual void sortSeq(int a[], int n) = 0;
};

class BobbleSort :public Sort
{
public:
	virtual void sortSeq(int  a[], int n);
};
class InsertSort :public Sort
{
public:
	virtual void sortSeq(int  a[], int n);
};
class SelectSort :public Sort
{
public:
	virtual void sortSeq(int a[], int n);
};

Context.h

#include"Sort.h"
class Context
{
private:
	Sort* sort;
public:
	Context(Sort*sort) 
	{
		this->sort = sort;
	}
	void sortS(int a[], int n)
	{
		sort->sortSeq(a, n);
	}
};

Bobble.cpp

#include"Sort.h"

void BobbleSort::sortSeq(int a[], int n)
{
	cout << "BobbleSort" << endl;
	if (n <= 1)
		return;
	int temp;
	for (int i = 0; i < n - 1; i++)
	{
		for (int j = 1; j < n - i; j++)
		{
			if (a[j] < a[j - 1])
			{
				temp = a[j];
				a[j] = a[j - 1];
				a[j - 1] = temp;
			}
		}
	}
}

Insert.cpp

#include "Sort.h"
void InsertSort::sortSeq(int a[], int n)
{
	cout << "InsertSort" << endl;
	if (n <= 1)
		return;
	int temp;
	for (int i = 1; i < n; i++)
	{
		for (int j = i - 1; j >= 0; j--)
		{
			if (a[j] > a[j + 1])
			{
				temp = a[j];
				a[j] = a[j + 1];
				a[j + 1] = temp;
			}
			else
				break;
		}
	}
}

Select.cpp

#include "Sort.h"
void SelectSort::sortSeq(int a[], int n)
{
	cout << "selectSort" << endl;
	if (n <= 1)
		return;
	int temp;
	for (int i = 0; i < n - 1; i++)
	{
		int minID = i;
		for (int j = i + 1; j < n; j++)
		{
			if (a[j] < a[minID])
				minID = j;
		}
		temp = a[i];
		a[i] = a[minID];
		a[minID] = temp;
	}
}

Main.cpp

#include"Context.h"
int main()
{
	const int n = 5;
	int a[n] = { 3,-5,-6,5,6 };
	for (int i = 0; i < n; i++)
	{
		cout << a[i] << " ";
	}
	cout << endl;
	Sort* s = new BobbleSort;
	Context* c = new Context(s);
	c->sortS(a, n);
	for (int i = 0; i < n; i++)
	{
		cout << a[i] << " ";
	}
	cout << endl;
	system("pause");
	return 0;
}

运行结果:
结果

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值