【发布时间】:2016-05-08 08:58:13
【问题描述】:
我在排序哈希表时遇到问题。我有比较数字、字母和冒泡排序算法的方法。排序输出不是我想要的,因为它按插入顺序打印哈希表(第一次插入 - 第一次打印),而我想要的是按升序键排序或按值升序排序。键是整数,值是字符串。 代码如下:
#include<iostream>
#include<string>
using namespace std;
const int size = 100;
class Binding
{
public:
int key;
string value;
Binding *next;
Binding(int key, string value)
{
this->key = key;
this->value = value;
this->next = NULL;
}
};
class HashTable
{
private:
Binding** tarray;
public:
HashTable()
{
array = new Binding*[size];
for(int i = 0; i < size; i++)
{
array[i] = NULL;
}
}
int insert(int key, string value)
{
int hash = (key % size);
Binding *record = array[hash];
Binding *previous = NULL;
if(record != NULL)
{
previous = record;
record = record->next;
}
else if(record == NULL)
{
record = new Binding(key, value);
if (previous == NULL)
{
array[hash] = record;
}
else
{
previous->next = record;
}
}
else
{
record->value = value;
}
}
int compareLetters(const void *a, const void *b)
{
Binding *A = (Binding*)a;
Binding* B = (Binding*)b;
int compare = strcmp(A->letter, B->letter);
if(compare == 0)
return 0;
else if(compare > 0)
return 1;
else if(compare < 0)
return -1;
}
int compareNumbers(const void *a, const void *b)
{
Binding *A = (Binding*)a;
Binding *B = (Binding*)b;
if(A->key > B->key)
return 1;
else if(A->key < B->key)
return -1;
else
return 0;
}
void bubble_sort()
{
Binding *temp;
for(int i=1; i<size; i++)
{
for(int j=0; j<size - i; j++)
{
if(compareNumbers(&array[j], &array[j+1]) == 1)
{
temp = array[j];
array[j] = array[j+1];
array[j+1] = temp;
}
}
}
}
【问题讨论】:
-
if(record != NULL){...}else if(record == NULL){...}else简直是穷举和错误的构造。 -
请不要删除问题并重新发布;如有必要,编辑您的问题以添加额外的细节。
-
int compareNumbers(const void *a, const void *b)停止使用void *。使用实际类型 (Binding *)。 -
@MyStaa 一个哈希表,就像你代码中的那个一样,是按哈希值排序的,哈希值是从 key 计算出来的。如果您更改订单,您将无法再按键访问该表。您需要的是基于排序树的 std::map。如果您不能使用地图,只需将数据复制到矢量中,然后对其进行排序并打印。
-
@MyStaa 假设您的插入方法有效(我没有检查它),您将不得不添加一个
at( key_type)方法来按键检索值。您还必须知道表中有多少元素(在insert中跟踪计数)。分配key_type的向量(这就是您需要计数的原因)将键值复制到该向量中并对其进行排序。然后,使用at方法使用向量中的键检索值。要遍历表,请遍历tarray中的每个列表。 [或者,您可以使用 Binding 向量,从而避免使用at]
标签: c++ sorting hashtable key-value bubble-sort