Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <iostream>
- #include <stdio.h>
- #include <stdlib.h>
- #include <string.h>
- #include "Profiler.h"
- using namespace std;
- Profiler profiler("HashTables");
- typedef struct {
- int id;
- char name[30];
- }Entry;
- int effort, flag;
- /*
- int Linear(int key, int i, int size)
- {
- return key % size;
- }
- */
- int HashFunction(int key, int i, int size)
- {
- return (key + i * i) % size;
- }
- void initializeTable(Entry* hash, int size)
- {
- for (int i = 0; i < size; i++)
- {
- hash[i].id = NULL;
- strcpy_s (hash[i].name, "empty");
- }
- }
- int HashInsert(Entry T[], int key, int size)
- {
- int i = 0;
- do
- {
- int j = HashFunction(key, i, size);
- if (T[j].id == NULL)
- {
- T[j].id = key;
- strcpy_s(T[j].name, "Name");
- return j;
- }
- else i++;
- } while (i != size);
- return 0;
- }
- int HashSearch(Entry T[], int key, int size)
- {
- int i = 0, j;
- do
- {
- j = HashFunction(key, i, size);
- effort++;
- if (T[j].id == key)
- {
- if (flag == 0) cout << "\nAt position " << j << "we found the element " << key;
- return j;
- }
- else i++;
- } while (i!=size || T[j].id != NULL);
- if (flag == 0) cout << "\ERR: element " << key << " not found\n";
- return 0;
- }
- int* generateAvgData(int n)
- {
- int* a = (int*)malloc(n * sizeof(int));
- FillRandomArray(a, n, 1, 1000, false, 0);
- return a;
- }
- int FillingFactor(int factor, int size)
- {
- return (size * factor / 100);
- }
- void HashPrint(Entry hash[], int size)
- {
- for (int i = 0; i < size; i++)
- cout << hash[i].id << " -> " << hash[i].name;
- }
- void DemoInsert ()
- {
- cout << "\nDemoInsert\n";
- int *a = generateAvgData(7);
- cout << "\nThe array inserted in the hash table: \n";
- for (int i = 0; i < 7; i++)
- cout << a[i] << " ";
- cout << endl;
- Entry insert[10];
- initializeTable(insert, 10);
- for (int i = 0; i < 10; i++)
- HashInsert(insert, a[i], 10);
- for (int i = 0; i < 10; i++)
- cout << "insert[" << i << "]= " << insert[i].id << endl;
- }
- void DemoFillingFactorInsert()
- {
- cout << "\nDemo Filling Factor Insert\n";
- int factor = FillingFactor(50, 10);
- cout << "the filling factor is 50% and we'll insert "<<factor<<" elements in a table with 10 positions"<<endl;
- int* a = generateAvgData(factor);
- cout << "\nThe array inserted in the hash table: \n";
- for (int i = 0; i < factor; i++)
- cout << a[i] << " ";
- cout << endl;
- Entry insert[10];
- initializeTable(insert, 10);
- for (int i = 0; i < 10; i++)
- cout << insert[i].id << " ";
- cout << endl;
- for (int i = 0; i < 10; i++)
- HashInsert(insert, a[i], 10);
- for (int i = 0; i < 10; i++)
- cout << "insert[" << i << "]= " << insert[i].id << endl;
- }
- int main()
- {
- DemoInsert();
- DemoFillingFactorInsert();
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement