我写了这个版本的插入排序算法,它允许用户选择升序排序还是排序降序。我在2000万的Integer上试过它,但它真的很慢。我该如何改进呢?
public Sorting insertionSort(int ordinamento) throws SortingException {
if (ordinamento != 0 && ordinamento != 1) throw new SortingException("ERRORE!");
for(int i=1; i<(this.array).size(); i++){
T elem=(this.array).get(i);
int j=i-1;
if (ordinamento == 0) {
while(j>=0 && (this.comparator).compare(elem, (this.array).get(j))<0){
(this.array).set(j+1, (this.array).get(j));
j--;
}
} else {
while(j>=0 && (this.comparator).compare(elem, (this.array).get(j))>0){
(this.array).set(j+1, (this.array).get(j));
j--;
}
}
(this.array).set(j+1, elem);
}
return this;
}
类结构是这样的:
public Sorting(Comparator<? super T> comparator) {
this.array = new ArrayList<>();
this.comparator = comparator;