해싱의 기본 동작은 새 데이터가 새로 입력되면, 가장 먼저 어떤 버킷에 넣을 것인지 결정해야 하는데 이 연산을 하는 기능이 해시알고리즘이다.
특정 데이터를 검색시에도 해시알고리즘 기능을 사용하면 어떤 버킷에서 찾을 것인지 결정되기 때문에 빠르게 검색할 수 있다.
자료가 저장되는 전체 저장소를 해시 테이블(Hash Table)이라고 한다.
해시 테이블은 여러 개의 버킷(Bucket)으로 나누어지는데, 주소록의 ㄱ,ㄴ,ㄷ,ㄹ과 같은 인덱스 페이지가 버킷이다.
버킷은 여러 개의 슬롯으로 구성되어 있는데, 슬롯은 버킷에 데이터가 저장되는 단위이다. 즉, 주소록에서 한 명의 주소를 적는 칸의 단위라고 보면 된다.
해시테이블의 형태 : 2차원 배열 (표)
해싱의 기초적인 연산은 자료가 새로 입력될 때 이 자료를 어떤 버킷에 넣을지 결정하는 것인데, 이를 해시 함수라고 한다.
해시 함수는 입력된 키 값으로 버킷의 번호를 찾아내는 함수이다.
주소록의 경우 이름의 첫 글자 자음으로 버킷 번호를 찾는다. (ex, 김 아무개는 ㄱ칸, 이 아무개는 ㅇ칸, 장 아무개는 ㅈ칸)
이러한 원리를 이용하여 해시 함수를 만들어보자.
#include<stdio.h>
#include<string.h>
#define BK 10
#define SL 1
void insertValue(int key);
bool findValue(int key);
int hashtable[BK][SL];
void main()
{
int data = 0;
memset(hashtable, 0 , sizeof(hashtable));
printf("키를 5개 입력하세요.\n");
for (int i = 0; i < 5; i++)
{
printf("%d번째 값을 입력하세요 : ", i + 1);
scanf_s("%d", &data);
insertValue(data);
}
printf("검색할 키를 입력하세요.\n");
scanf_s("%d", &data);
bool search = findValue(data);
if (search)
{
printf("검색되었습니다.\n");
}
else
{
printf("안 검색되었습니다.\n");
}
}
int Hash(int key)
{
int rest = key % 10 ;
return rest;
}
void insertValue(int key)
{
int bucket = Hash(key);
printf("bucket : %d\n", bucket);
if (hashtable[bucket][0] == 0)
{
hashtable[bucket][0] = key;
printf("hashtable : %d\n", hashtable[bucket][0]);
}
}
bool findValue(int key)
{
int bucket = Hash(key);
if (hashtable[bucket][0] == key)
{
return true;
}
else
{
return false;
}
}
#include<stdio.h>
#include<string.h>
#define BK 10
#define SL 3
void insertValue(int key);
bool findValue(int key);
int hashtable[BK][SL];
void main()
{
int data = 0;
memset(hashtable, 0 , sizeof(hashtable));
printf("키를 5개 입력하세요.\n");
for (int i = 0; i < 5; i++)
{
printf("%d번째 값을 입력하세요 : ", i + 1);
scanf_s("%d", &data);
insertValue(data);
}
printf("검색할 키를 입력하세요.\n");
scanf_s("%d", &data);
bool search = findValue(data);
if (search)
{
printf("검색되었습니다.\n");
}
else
{
printf("안 검색되었습니다.\n");
}
}
int Hash(int key)
{
int rest = key % 10 ;
return rest;
}
void insertValue(int key)
{
int bucket = Hash(key);
printf("bucket : %d\n", bucket);
for (int i = 0; i < SL; i++)
{
if (hashtable[bucket][i] == 0)
{
hashtable[bucket][i] = key;
printf("hashtable : %d\n", hashtable[bucket][0]);
break;
}
}
}
bool findValue(int key)
{
int bucket = Hash(key);
for (int i = 0; i < SL; i++)
{
if (hashtable[bucket][i] == key)
{
return true;
}
}
return false;
}
``