이러한 속성은 당신을 위해 충분하지 않습니다 :
- 더 충돌
- 최악의 경우 키 룩업 성능 =>
O(log n)
다음 개념 증명 구현 :
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX_PAIRS 3
#define KEY_SIZE 20
#define VALUE_OR_KEY_NOT_FOUND(v) ((v==NULL)? "(__KEY_NOT_FOUND__)":v)
typedef struct {
char Key[KEY_SIZE];
char Val[KEY_SIZE];
} Pair;
typedef struct {
unsigned int lastPairIndex;
Pair pairs[MAX_PAIRS];
} HashTable;
int comparePairs(const void * a, const void * b)
{
return strcmp(((Pair *)a)->Key, ((Pair *)b)->Key);
}
void hashInsert(HashTable * hashTable, char * key, char * val) {
unsigned int ix = hashTable->lastPairIndex++;
strcpy(hashTable->pairs[ix].Key,key);
strcpy(hashTable->pairs[ix].Val,val);
}
void hashFinalize(HashTable * hashTable) {
qsort(hashTable->pairs, MAX_PAIRS, sizeof(Pair), comparePairs);
}
char * hashLookup(HashTable * hashTable, char * key) {
char * r = bsearch(key, hashTable->pairs, MAX_PAIRS, sizeof(Pair), comparePairs);
if (r != NULL)
return r + KEY_SIZE;
return NULL;
}
int main()
{
HashTable ht = {0};
char * res;
char * key_1 = "jkl";
char * key_2 = "oops";
hashInsert(&ht, "jkl", "some val");
hashInsert(&ht, "def", "other val");
hashInsert(&ht, "abc", "this val");
hashFinalize(&ht);
res = hashLookup(&ht, key_1);
printf("\"%s\" key => value: \"%s\"\n", key_1, VALUE_OR_KEY_NOT_FOUND(res));
res = hashLookup(&ht, key_2);
printf("\"%s\" key => value: \"%s\"\n", key_2, VALUE_OR_KEY_NOT_FOUND(res));
return 0;
}
많은 오류가 확인되지 않았습니다. 예를 들어 삽입 할 때와 같은 이미 거기에 존재할 수 있습니다. 이것은 단지 개념 증명입니다. O(log n)
키가 사전 순으로 정렬되어 키 조회가 2 진 검색 알고리즘으로 수행 될 수 있으므로 키 조회 성능이 달성됩니다. HTH!
이 해시 테이블로 무엇을하고 있습니까? 사용할 모든 키를 열거 할 수 있으므로 사전 계산 된 트리와 같은 다른 데이터 구조를 사용할 수 있습니다. – user57368