前些天学过策略模式,最近重温了几种常用的简单排序算法,想到了策略模式,就实际操练一下。存在的问题是当存在参数数量不同时,怎么调用(如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;
}
运行结果: