Softwaredesign: Beispiel: Parametrisierbares Sortieren eines Feldes |
abstract
public
class SortAlgorithm {
protected
CompareFunction c;
protected
SortAlgorithm(CompareFunction c) {
this.c = c;
}
abstract
void sort(int [] a);
}
|
public
class BubbleSort extends SortAlgorithm {
//--------------------
// the constructor
// defines the compare function
public
BubbleSort(CompareFunction c) {
super(c);
}
//--------------------
public
void sort(int [] a) {
// simple bubble sort
// --> 2 nested loops
for (int i = a.length -1;
i >= 0;
--i ) {
for (int j = 0;
j < i;
++j ) {
if ( c.compare(a[j], a[j+1]) > 0 ) {
int tmp = a[j];
a[j] = a[j+1];
a[j+1] = tmp;
}
}
}
}
}
|
public
class QuickSort extends SortAlgorithm {
//--------------------
// the constructor
// defines the compare function
public
QuickSort(CompareFunction c) {
super(c);
}
//--------------------
public
void sort(int [] a) {
// some more complicated code
// ...
// if ( c.compare(..., ...) ) ...
}
}
|
public
interface CompareFunction {
abstract
public
int compare(int i, int j);
}
|
Letzte Änderung: 13.04.2012 | © Prof. Dr. Uwe Schmidt |