78 lines
2.3 KiB
Java
78 lines
2.3 KiB
Java
import java.util.Collections;
|
|
|
|
public class Inventar {
|
|
private Gegenstand[] gegenstaende;
|
|
|
|
public Inventar() {
|
|
this.gegenstaende = new Gegenstand[10];
|
|
gegenstaende[0] = new Gegenstand ("Bogen", 20);
|
|
gegenstaende[1] = new Gegenstand ("Gürtel", 10);
|
|
gegenstaende[2] = new Gegenstand ("Helm", 25);
|
|
gegenstaende[3] = new Gegenstand ("Pfeile", 5);
|
|
gegenstaende[4] = new Gegenstand ("Ring", 7);
|
|
gegenstaende[5] = new Gegenstand ("Schild", 30);
|
|
gegenstaende[6] = new Gegenstand ("Schwert", 18);
|
|
gegenstaende[7] = new Gegenstand ("Rüstung", 22);
|
|
gegenstaende[8] = new Gegenstand ("Stiefel", 16);
|
|
gegenstaende[9] = new Gegenstand ("Kette", 18);
|
|
|
|
gegenstaende = sortArray(gegenstaende);
|
|
|
|
for(int i = 0; i < gegenstaende.length; i++) {
|
|
System.out.println(gegenstaende[i].getName());
|
|
}
|
|
|
|
// Test binary search:
|
|
int position = binarySearch(gegenstaende, gegenstaende[2].getName());
|
|
System.out.println("Found " + gegenstaende[position].getName() + " at position: " + position + " with 'ausdauer': " + gegenstaende[position].getAusdauer());
|
|
}
|
|
|
|
public Gegenstand[] sortArray(Gegenstand[] gegenstaende) {
|
|
// Insertion sort
|
|
|
|
for (int index = 1; index < gegenstaende.length; index++) {
|
|
Gegenstand entry = gegenstaende[index];
|
|
int previousIndex = index;
|
|
|
|
while (previousIndex > 0 && gegenstaende[previousIndex - 1].getName().compareTo(entry.getName()) > 0) {
|
|
gegenstaende[previousIndex] = gegenstaende[previousIndex - 1];
|
|
previousIndex--;
|
|
}
|
|
gegenstaende[previousIndex] = entry;
|
|
}
|
|
|
|
return gegenstaende;
|
|
}
|
|
|
|
public int binarySearch(Gegenstand[] gegenstaende, String searchedName) {
|
|
int low = 0;
|
|
int high = gegenstaende.length-1;
|
|
|
|
while(low <= high) {
|
|
int pivot = (low + high) / 2;
|
|
|
|
int compareToResult = gegenstaende[pivot].getName().compareTo(searchedName);
|
|
if(compareToResult == 0) {
|
|
return pivot;
|
|
} else if (compareToResult < 0) {
|
|
low = pivot + 1;
|
|
} else if (compareToResult > 0) {
|
|
high = pivot -1;
|
|
}
|
|
}
|
|
return -1;
|
|
}
|
|
|
|
public void lineareSuche(String name) {
|
|
// to do
|
|
}
|
|
|
|
public Gegenstand[] getGegenstaende() {
|
|
return gegenstaende;
|
|
}
|
|
|
|
public void maxAusdauer() {
|
|
// to do
|
|
}
|
|
}
|