Skip to content

Instantly share code, notes, and snippets.

@Dantali0n
Created November 16, 2016 07:59
Show Gist options
  • Save Dantali0n/68bb8cc0553b642d2ce957535ac85ddc to your computer and use it in GitHub Desktop.
Save Dantali0n/68bb8cc0553b642d2ce957535ac85ddc to your computer and use it in GitHub Desktop.
Java abstract class for sorting classes according to Algorithms fourth edition (ISBN: 978-0-321-57351-3)
/*****************************************************************************
Written and Copyright (C) by Corne Lukken
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*****************************************************************************/
import java.util.Comparator;
import java.util.List;
/**
* Defined sort class standard as described in book.
* @author Corne Lukken
* @urk https://dantalion.nl
*/
public abstract class BaseSort<T> {
protected List<T> list;
protected Comparator comparator;
protected long comparisons = 0;
protected long swaps = 0;
public BaseSort(List<T> list, Comparator<T> comparator) {
this.list = list;
this.comparator = comparator;
}
public abstract void sort();
public boolean less(T a, T b) {
comparisons++;
return comparator.compare(a, b) < 0;
}
public void exch(int i, int j) {
swaps++;
T tempT = list.get(j);
list.set(j, list.get(i));
list.set(i, tempT);
}
public boolean isSorted() {
for(int i = 1; i < list.size(); i++) {
if(less(list.get(i), list.get(i-1))) return false;
}
return true;
}
public abstract void show();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment