資料結構›Ch8 雜湊
第 20 題/共 37 題
◀ DS 20/37
20. Open Addressing、Deleted Slot、Hash Search
#DS-08-020中Open AddressingDeleted SlotHash Search

Consider the following two functions written in C language for the insertion into a hash table and the deletion from the table:

void insert(int table[], int size, int key) {
    int index;
    for (int i = 0; i < size; i++) {
        index = (key % size + i * i) % size;
        if (table[index] == -1 || table[index] == -2) {
            table[index] = key;
            return;
        }
    }
}
void delete(int table[], int size, int key) {
    int index;
    for (int i = 0; i < size; i++) {
        index = (key % size + i * i) % size;
        if (table[index] == key) {
            table[index] = -2;
            return;
        }
    }
}

Given that the keys are all non-negative integers and the keys to be deleted are always in the hash table. Which of the following implementations correctly searches for a specific key in the hash table, considering collision handling and the presence of deleted slots?

(A)

int search(int table[], int size, int key) {
    int index;
    for (int i = 0; i < size; i++) {
        index = (key % size + i) % size;
        if (table[index] == -1) {
            return -1;
        }
        if (table[index] == key) {
            return index;
        }
    }
    return -1;
}

(B)

int search(int table[], int size, int key) {
    int index;
    for (int i = 0; i < size; i++) {
        index = (key % size + i * i) % size;
        if (table[index] == key) {
            return index;
        }
        if (table[index] == -1 || table[index] == -2) {
            return -1;
        }
    }
    return -1;
}

(C)

int search(int table[], int size, int key) {
    int index;
    for (int i = 0; i < size; i++) {
        index = (key % size + i * i) % size;
        if (table[index] == -1) {
            return -1;
        }
        if (table[index] == key) {
            return index;
        }
        if (table[index] == -2) {
            continue;
        }
    }
    return -1;
}

(D)

int search(int table[], int size, int key) {
    int index;
    for (int i = 0; i < size; i++) {
        index = (key % size + i * i) % size;
        if (table[index] == -2) {
            return -1;
        }
        if (table[index] == key) {
            return index;
        }
    }
    return -1;
}
📄 成大114
跳轉到第題
▤完整推導請見《WH 資工筆記 · 資料結構》Ch8 雜湊
本章題號 · 1–20 / 37