C ++ - 使用关联数组,按值排序后无法按键搜索

时间:2016-05-21 15:05:20

标签: c++ search associative-array quicksort binary-search

在下面的代码中,我有一个关联数组,其中包含字母表中的字母作为键和与之关联的任意值。我已经实现了一个快速排序功能,可以根据值降序对它们进行排序。我有一个二进制搜索功能来搜索特定的键(字母)。二进制搜索在我排序之前工作正常,但在我排序后,只有一些字母被发现使用它。尝试自己完成它,我在执行quickSort()之前和之后循环遍历数组,它似乎确认这些值仍然存在,尽管它们已经排序。我做错了什么?

#include <iostream>
#include <array>

using namespace std;

int binarySearch(int arr[][2], int value, int left, int right)
{
    while (left <= right)
    {
        int middle = (left + right) / 2;
        if (arr[middle][0] == value)
            return middle;
        else if (arr[middle][0] > value)
            right = middle - 1;
        else
            left = middle + 1;
    }
    return -1;
}

void quickSort(int arr[][2], int left, int right)
{
    int i = left, j = right;
    int tmp1, tmp2;
    int pivot = arr[(left + right) / 2][1];

    /* partition */
    while (i <= j)
    {
        while (arr[i][1] > pivot)
            i++;
        while (arr[j][1] < pivot)
            j--;
        if (i <= j)
        {
            tmp1 = arr[i][0];
            tmp2 = arr[i][1];

            arr[i][0] = arr[j][0];
            arr[i][1] = arr[j][1];

            arr[j][0] = tmp1;
            arr[j][1] = tmp2;

            i++;

            j--;
        }
    };

    /* recursion */
    if (left < j)
        quickSort(arr, left, j);
    if (i < right)
        quickSort(arr, i, right);

}

int main()
{
    const int alphLength = 26;
    int assocArr[alphLength][2] = { {'A', 5},  {'B', 2}, {'C', 4}, {'D', 3},  {'E', 1}, {'F', 0}, {'G', 0}, {'H', 0}, {'I', 0},
        {'J', 0}, {'K', 0}, {'L', 0}, {'M', 0}, {'N', 0}, {'O', 0}, {'P', 75}, {'Q', 0}, {'R', 0},
        {'S', 0}, {'T', 0}, {'U', 0}, {'V', 0}, {'W', 0}, {'X', 50}, {'Y', 0}, {'Z', 100} };

char a;
char searchLetter = 'Z';

for (int i = 0; i < alphLength; i++)
{
    a = assocArr[i][0];
    cout << "index " << i << ": " << a << endl;
}

cout << "found " << searchLetter << " before quickSort() at " << binarySearch(assocArr, searchLetter, 0, alphLength-1) << endl;

quickSort(assocArr, 0, alphLength-1);

for (int i = 0; i < alphLength; i++)
{
    a = assocArr[i][0];
    cout << "index " << i << ": " << a << endl;
}

cout << "found " << searchLetter << " after quickSort() at " << binarySearch(assocArr, searchLetter, 0, alphLength-1) << endl;

}

1 个答案:

答案 0 :(得分:1)

二进制搜索仅适用于已排序的数组,它们需要按照用于在搜索中比较它们的相同条件进行排序。你的数组按字母升序排序,你的二进制搜索按字母升序搜索,这样就行了。然后,您可以按值对其进行排序,从而对字母进行加密。然后再按字母升序进行二进制搜索,这不会起作用,因为数组不再按字母升序排序。