我使用几种实现SORTER接口的方法编写了一个抽象分类器。
分拣机界面
<T> void sort(@NotNull final Comparator<T> comparator, @NotNull final List<T> list);
AbstractSorter
public abstract class AbstractSorter implements Sorter, ObservableSorter{
private SorterType type;
protected List<SorterListener> listeners;
protected AbstractSorter(SorterType type) {
this.type = type;
listeners = new LinkedList<>();
}
protected <T> boolean greater(@NotNull List<T> list, int i, int j, @NotNull Comparator<T> comp) {
listeners.forEach(e -> e.greater(0,0));
return comp.compare(list.get(i),list.get(j)) > 0;
}
protected <T> void swap(@NotNull List<T> list, int i, int j){
T aux = list.get(i);
list.set(i, list.get(j));
list.set(j, aux);
/*Updates Observers*/
listeners.stream().forEach(e -> e.swap(i,j));
}
protected <T> void compSwap(@NotNull List<T> list, int i, int j,@NotNull Comparator<T> comp){
if(greater(list,i,j,comp))swap(list, i,j);
}
public abstract <T> void sort(@NotNull Comparator<T> comparator, @NotNull List<T> list );
@NotNull
public SorterType getType() {
return type;
}
@Override
public void addSorterListener(@NotNull SorterListener sorterListener) {listeners.add(sorterListener);}
@Override
public void removeSorterListener(@NotNull SorterListener sorterListener) throws IllegalArgumentException{
if(!listeners.contains(sorterListener)) throw new IllegalArgumentException("Listener not found");
listeners.remove(sorterListener);
}
}
最后我的bubbleort
public class BubbleSort extends AbstractSorter{
public BubbleSort() {super(SorterType.BUBBLE);}
@Override
public <T> void sort(@NotNull Comparator<T> comparator, @NotNull List<T> list) {
/*Updates Observers*/
listeners.stream().forEach(e-> e.box(0, list.size()));
System.out.println(list.size());
boolean swapped = true;
int j = 0;
int size = list.size();
while(swapped){
swapped = false;
j++;
for (int i = 0; i < size - j ; i++) {
if(greater(list,i,i+1,comparator)){
swap(list,i,i+1);
System.out.println(i + " " + (i+1));
swapped = true;
}
}
}
}
问题是,当我测试我的冒泡排序多达1000个元素时,它可以正常工作,但是当我列出5000个元素时,需要花费大量时间(10分钟或更长时间)来完成任务,我无法理解为什么。