fix(C): fix array_hash_map.c and bucket_sort.c (#1272)

* fix: Fix coding error, https://github.com/krahets/hello-algo/discussions/440#discussioncomment-8958379

* fix: Fix issue 1237 https://github.com/krahets/hello-algo/issues/1237

* Update array_hash_map.c

* Update bucket_sort.c

* Update bucket_sort.c

* Update array_hash_map.c

* Update bucket_sort.c

* Update bucket_sort.c

---------

Co-authored-by: Yudong Jin <krahets@163.com>
This commit is contained in:
Lanjing Gong
2024-04-12 03:03:18 +08:00
committed by GitHub
parent 49e6a208f6
commit aca850244b
4 changed files with 72 additions and 108 deletions
+13 -10
View File
@@ -7,7 +7,7 @@
#include "../utils/common.h"
/* 哈希表默认大小 */
#define HASHTABLE_CAPACITY 100
#define MAX_SIZE 100
/* 键值对 int->string */
typedef struct {
@@ -23,18 +23,21 @@ typedef struct {
/* 基于数组实现的哈希表 */
typedef struct {
Pair *buckets[HASHTABLE_CAPACITY];
Pair *buckets[MAX_SIZE];
} ArrayHashMap;
/* 构造函数 */
ArrayHashMap *newArrayHashMap() {
ArrayHashMap *hmap = malloc(sizeof(ArrayHashMap));
for (int i=0; i < MAX_SIZE; i++) {
hmap->buckets[i] = NULL;
}
return hmap;
}
/* 析构函数 */
void delArrayHashMap(ArrayHashMap *hmap) {
for (int i = 0; i < HASHTABLE_CAPACITY; i++) {
for (int i = 0; i < MAX_SIZE; i++) {
if (hmap->buckets[i] != NULL) {
free(hmap->buckets[i]->val);
free(hmap->buckets[i]);
@@ -45,7 +48,7 @@ void delArrayHashMap(ArrayHashMap *hmap) {
/* 哈希函数 */
int hashFunc(int key) {
int index = key % HASHTABLE_CAPACITY;
int index = key % MAX_SIZE;
return index;
}
@@ -83,13 +86,13 @@ void pairSet(ArrayHashMap *hmap, MapSet *set) {
int i = 0, index = 0;
int total = 0;
/* 统计有效键值对数量 */
for (i = 0; i < HASHTABLE_CAPACITY; i++) {
for (i = 0; i < MAX_SIZE; i++) {
if (hmap->buckets[i] != NULL) {
total++;
}
}
entries = malloc(sizeof(Pair) * total);
for (i = 0; i < HASHTABLE_CAPACITY; i++) {
for (i = 0; i < MAX_SIZE; i++) {
if (hmap->buckets[i] != NULL) {
entries[index].key = hmap->buckets[i]->key;
entries[index].val = malloc(strlen(hmap->buckets[i]->val) + 1);
@@ -107,13 +110,13 @@ void keySet(ArrayHashMap *hmap, MapSet *set) {
int i = 0, index = 0;
int total = 0;
/* 统计有效键值对数量 */
for (i = 0; i < HASHTABLE_CAPACITY; i++) {
for (i = 0; i < MAX_SIZE; i++) {
if (hmap->buckets[i] != NULL) {
total++;
}
}
keys = malloc(total * sizeof(int));
for (i = 0; i < HASHTABLE_CAPACITY; i++) {
for (i = 0; i < MAX_SIZE; i++) {
if (hmap->buckets[i] != NULL) {
keys[index] = hmap->buckets[i]->key;
index++;
@@ -129,13 +132,13 @@ void valueSet(ArrayHashMap *hmap, MapSet *set) {
int i = 0, index = 0;
int total = 0;
/* 统计有效键值对数量 */
for (i = 0; i < HASHTABLE_CAPACITY; i++) {
for (i = 0; i < MAX_SIZE; i++) {
if (hmap->buckets[i] != NULL) {
total++;
}
}
vals = malloc(total * sizeof(char *));
for (i = 0; i < HASHTABLE_CAPACITY; i++) {
for (i = 0; i < MAX_SIZE; i++) {
if (hmap->buckets[i] != NULL) {
vals[index] = hmap->buckets[i]->val;
index++;