以下是使用Java实现冒泡排序、选择排序和快速排序的示例代码,使用策略模式实现:
- 首先,定义一个策略接口 SortingStrategy,包含一个排序方法 sort:
public interface SortingStrategy {
void sort(int[] array);
}
- 然后,实现三个具体的策略类,分别代表不同的排序算法:
public class BubbleSortStrategy implements SortingStrategy {
@Override
public void sort(int[] array) {
int n = array.length;
for (int i = 0; i < n - 1; i++) {
for (int j = 0; j < n - i - 1; j++) {
if (array[j] > array[j + 1]) {
int temp = array[j];
array[j] = array[j + 1];
array[j + 1] = temp;
}
}
}
System.out.println("Sorting using bubble sort: " + Arrays.toString(array));
}
}
public class SelectionSortStrategy implements SortingStrategy {
@Override
public void sort(int[] array) {
int n = array.length;
for (int i = 0; i < n - 1; i++) {
int minIndex = i;
for (int j = i + 1; j < n; j++) {
if (array[j] < array[minIndex]) {
minIndex = j;
}
}
int temp = array[minIndex];
array[minIndex] = array[i];
array[i] = temp;
}
System.out.println("Sorting using selection sort: " + Arrays.toString(array));
}
}
public class QuickSortStrategy implements SortingStrategy {
@Override
public void sort(int[] array) {
quickSort(array, 0, array.length - 1);
System.out.println("Sorting using quick sort: " + Arrays.toString(array));
}
private void quickSort(int[] array, int low, int high) {
if (low < high) {
int pivot = partition(array, low, high);
quickSort(array, low, pivot - 1);
quickSort(array, pivot + 1, high);
}
}
private int partition(int[] array, int low, int high) {
int pivot = array[high];
int i = low - 1;
for (int j = low; j < high; j++) {
if (array[j] < pivot) {
i++;
int temp = array[i];
array[i] = array[j];
array[j] = temp;
}
}
int temp = array[i + 1];
array[i + 1] = array[high];
array[high] = temp;
return i + 1;
}
}
- 接下来,创建一个上下文类 SortingContext,该类包含一个策略接口的成员变量和一个执行排序的方法 executeSort:
public class SortingContext {
private SortingStrategy sortingStrategy;
public SortingContext(SortingStrategy sortingStrategy) {
this.sortingStrategy = sortingStrategy;
}
public void executeSort(int[] array) {
sortingStrategy.sort(array);
}
}
- 最后,可以使用策略模式进行排序操作:
public class Main {
public static void main(String[] args) {
int[] array = {5, 2, 8, 3, 1};
// 选择排序策略并创建相应的策略对象
SortingStrategy sortingStrategy = new BubbleSortStrategy();
// 或者 SortingStrategy sortingStrategy = new SelectionSortStrategy();
// 或者 SortingStrategy sortingStrategy = new QuickSortStrategy();
// 创建上下文对象
SortingContext context = new SortingContext(sortingStrategy);
// 执行排序操作
context.executeSort(array);
}
}
在上述示例中,我们定义了三种排序策略:冒泡排序、选择排序和快速排序。根据需求,我们选择其中一种策略,并将其传递给上下文对象 SortingContext 的构造方法。然后,通过调用 executeSort 方法来执行排序操作。
输出结果将根据所选的排序策略不同而有所不同。
需要注意的是,策略模式允许在运行时动态选择不同的策略,因此可以根据实际需求灵活地切换排序算法,而不需要修改上下文类的代码。
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。