
Untitled
By: a guest on
Jun 17th, 2012 | syntax:
Java | size: 1.74 KB | hits: 15 | expires: Never
package Blatt09;
public class HashLinQuad {
private final int[] table;
private int size; // current number of elements
private final int capacity;
// Konstruktor
private HashLinQuad(int cap) {
capacity = cap;
table = new int[cap];
}
public int addLin(int obj) {
if (size == capacity) { // Endlosschleifen vermeiden
System.out.println("Hashtabelle ist voll!");
return 0;
}
int position = obj % capacity;
int collision = 0;
while (table[position] != 0) { // Kollision!
collision++;
position++;
if (position > capacity) { // im "Rahmen" bleiben
position %= capacity;
}
}
table[position] = obj;
return collision;
}
public int addQuad(int obj) {
if (size == capacity) {
System.out.println("Hashtabelle ist voll!");
return 0;
}
int position = obj % capacity;
int collision = 0;
int counter = 0;
while (table[position] != 0) {
collision++;
counter++;
position += counter * counter;
if (position > capacity) {
position %= capacity;
}
}
table[position] = obj;
return collision;
}
@Override
public String toString() {
String str = "";
for (int element : table) { // durch die Tabelle iterieren & ausgeben
str += " " + element;
}
return str;
}
public static void main(String[] args) {
HashLinQuad lTable = new HashLinQuad(1249);
HashLinQuad qTable = new HashLinQuad(1249);
int linCol = 0;
int quadCol = 0;
for (int i = 0; i < 1000; i++) {
int obj = (int) (Math.random() * 1000);
linCol += lTable.addLin(obj); // Kollisionen zaehlen
quadCol += qTable.addQuad(obj);
}
System.out.println("linear: " + linCol);
System.out.println("quadratisch: " + quadCol);
}
}