Benutzer:Riemer

Aus ProgrammingWiki

Wiki-Quelltext dieser Seite.

<language>Java</language>
<run id="4f6a02066116e">
public Object DataItem(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() {
		System.out.print("Hash Table: ");
		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(item) {
		int key = item.getKey();
		int hashVal = hashFunction(key); // hash the key
		// until empty cell or -1,
		while (hashArray[hashVal] != null/* && hashArray[hashVal].getKey() != -1 */) {
			++hashVal; // go to next cell
			hashVal %= arraySize; // wraparound if necessary
		}
		hashArray[hashVal] = item; // insert item
	}

	Object delete(int key) {
		int hashVal = hashFunction(key);

		while (hashArray[hashVal] != null) // until empty cell,
		{
			if (hashArray[hashVal].getKey() == key) {
//				DataItem temp = hashArray[hashVal]; // save item
				// hashArray[hashVal] = bufItem; // delete item
				return hashArray[hashVal] = null;
//				return temp;
			}
			++hashVal; // go to next cell
			hashVal %= arraySize; // wraparound if necessary
		}
		return null; // can't find item
	}

	Object find(int key) // find item with key
	{
		int hashVal = hashFunction(key); // hash the key

		while (hashArray[hashVal] != null) // until empty cell,
		{
			if (hashArray[hashVal].getKey() == key)
				return hashArray[hashVal]; // found, return item
			++hashVal; // go to next cell
			hashVal %= arraySize; // wraparound if necessary
		}
		return null; // can't find item
	}
return this;
}

void fillHashTable(Object theHashTable) {

int aKey;

aKey = 1;
aDataItem = DataItem(aKey);
theHashTable.insert(aDataItem);

aKey = 3;
aDataItem = DataItem(aKey);
theHashTable.insert(aDataItem);

aKey = 4;
aDataItem = DataItem(aKey);
theHashTable.insert(aDataItem);

aKey = 8;
aDataItem = DataItem(aKey);
theHashTable.insert(aDataItem);

aKey = 9;
aDataItem = DataItem(aKey);
theHashTable.insert(aDataItem);

aKey = 12;
aDataItem = DataItem(aKey);
theHashTable.insert(aDataItem);

aKey = 13;
aDataItem = DataItem(aKey);
theHashTable.insert(aDataItem);

}

int aKey, size;

size = 15;
theHashTable = HashTable(size);

fillHashTabke(theHashTable);

theHashTable.displayTable();

aKey = 23;
aDataItem = DataItem(aKey);
theHashTable.insert(aDataItem);
theHashTable.displayTable();

theHashTable.delete(9);
theHashTable.displayTable();

aDataItem = theHashTable.find(aKey);
if (aDataItem != null) {
	System.out.println(aKey + " wurde gefunden!");
} else {
	System.out.println(aKey + " wurde nicht gefunden!");
}
</run>