/**
* 排序接口
*/
public interface Sortinterface {
void sort(int[] array);
}
/**
* 冒泡排序
*/
public class BubbleSort implements Sortinterface {
@Override
public void sort(int[] arr) {
for (int i = 0; i < arr.length - 1; i++) {
for (int j = 0; j < arr.length - 1 - i; j++) {
if (arr[j] > arr[j + 1]) {
int temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
}
}
}
}
}
/**
* 希尔排序
*/
public class HillSort implements Sortinterface {
@Override
public void sort(int[] a) {
int n=a.length;
int gap=n/2;
while(gap>=1){
for(int i=gap;i<a.length;i++){
int j=0;
int temp = a;
for(j=i-gap;j>=0 && temp<a[j];j=j-gap){
a[j+gap] = a[j];
}
a[j+gap] = temp;
}
gap = gap/2;
}
}
}
public class StrategyDesign {
//策略对象
private Sortinterface sort;
public StrategyDesign(Sortinterface sort) {
this.sort = sort;
}
public Sortinterface getSort() {
return sort;
}
public void setSort(Sortinterface sort) {
this.sort = sort;
}
public void sort(int[] arr){
sort.sort(arr);
}
}
public class Test {
public static void main(String[] args) {
int[] buf ={2,7,8,9,9,10,3,4,5,6,12};
int[] buf2 ={2,6,7,8,9,3,4,5,9,10,12};
//策略环境类
StrategyDesign design = new StrategyDesign(new BubbleSort());
BubbleSort bubbleSort = new BubbleSort();
design.setSort(bubbleSort);
design.sort(buf);
System.out.println(Arrays.toString(buf));
HillSort hillSort = new HillSort();
//可以动态带注入自己需要的策略
design.setSort(hillSort);
design.sort(buf2);
System.out.println(Arrays.toString(buf2));
}
}
欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/) | 黑马程序员IT技术论坛 X3.2 |