Benutzer:Riemer
Aus ProgrammingWiki
Wiki-Quelltext dieser Seite.
<language>Java</language>
<popup name="Klassen-Definitionen">
<code id="4f6ca2b733235">
public Object Elem(int d) {
int data = d;
int getKey() {
return data;
}
return this;
}
public Object HashTable(int size) {
int arraySize = size;
Object[] hashArray = new Object[arraySize];
for(i = 0; i < arraySize; i++) {
hashArray[i] = null;
}
void displayTable() {
for (int i = 0; i < arraySize; i++) {
if (hashArray[i] != null)
System.out.print(hashArray[i].getKey() + " ");
else
System.out.print("# ");
}
System.out.println("");
}
int hashFunction(int key) {
return key % arraySize;
}
void insert(elem) {
int key = elem.getKey();
int hashVal = hashFunction(key);
while (hashArray[hashVal] != null) {
++hashVal;
hashVal %= arraySize;
}
hashArray[hashVal] = elem;
}
Object remove(int key) {
int hashVal = hashFunction(key);
while (hashArray[hashVal] != null)
{
if (hashArray[hashVal].getKey() == key) {
return hashArray[hashVal] = null;
}
++hashVal;
hashVal %= arraySize;
}
return null;
}
Object find(int key)
{
int hashVal = hashFunction(key);
while (hashArray[hashVal] != null)
{
if (hashArray[hashVal].getKey() == key)
return hashArray[hashVal];
++hashVal;
hashVal %= arraySize;
}
return null;
}
return this;
}
void fillHashTable(Object hashTable, int numberOfKeys) {
/* int key;
key = 1;
elem = Elem(key);
theHashTable.insert(elem);
key = 3;
elem= Elem(key);
theHashTable.insert(elem);
key = 4;
elem = Elem(key);
theHashTable.insert(elem);
key = 8;
elem = Elem(key);
theHashTable.insert(elem);
key = 9;
elem = Elem(key);
theHashTable.insert(elem);
key = 12;
elem = Elem(key);
theHashTable.insert(elem);
key = 13;
elem = Elem(key);
theHashTable.insert(elem);
*/
for (int i = 0; i < numberOfKeys; i++) {
key = (int) (Math.random() * 10 * size);
elem = Elem(key);
hashTable.insert(elem);
}
}
</code></popup>
<run id="4f6ca2b73358e">
size = 17;
n = 10;
hashTable = HashTable(size);
fillHashTable(hashTable, n);
hashTable.displayTable();
/*key = 23;
elem = Elem(key);
theHashTable.insert(elem);
theHashTable.displayTable();
theHashTable.remove(9);
theHashTable.displayTable();
elem = theHashTable.find(key);
if (elem != null) {
System.out.println(key+ " wurde gefunden!");
} else {
System.out.println(key + " wurde nicht gefunden!");
}
*/
</run>