所以我有两个数组,一个有一些n个字符(可能在1000-2000左右),第二个有完全相同的n个整数。字符代表单词,并在我的树中整数出现这些单词的数量。我想对它进行排序,因此出现次数最多的单词是第一位,第二位是第二位等等。有人可以借给我一只手吗?我还没有采用数据结构/算法类,所以我遇到了问题。
我的代码:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define ARRAY_SIZE(a) sizeof(a)/sizeof(a[0])
#define ALPHABET_SIZE (26)
// Converts key current character into index
// use only 'a' through 'z' and lower case
#define CHAR_TO_INDEX(C) ((int)C - (int)'A')
#define INDEX_TO_CHAR(IX) ('A' + IX)
char words[3000][40]={{0}};
int counters[3000]={0};
int wordnr=0;
typedef struct trie_node trie_node_t;
struct trie_node
{
int counter;
trie_node_t *children[ALPHABET_SIZE];
};
typedef struct trie trie_t;
struct trie
{
trie_node_t *root;
int count;
};
// Returns new trie node
trie_node_t *getNode(void)
{
trie_node_t *pNode = NULL;
pNode = (trie_node_t *)malloc(sizeof(trie_node_t));
if( pNode )
{
int i;
pNode->counter = 0;
for(i = 0; i < ALPHABET_SIZE; i++)
{
pNode->children[i] = NULL;
}
}
return pNode;
}
// Initializes trie
void initialize(trie_t *pTrie)
{
pTrie->root = getNode();
pTrie->count = 0;
}
void setorder_rec(trie_node_t *pCrawl, char *str, int n)
{
if (pCrawl == NULL) return;
if (pCrawl->counter) {
str[n]='\0';
strcpy(words[wordnr],str);
words[wordnr][strlen(str)]='\0';
counters[wordnr]=pCrawl->counter;
wordnr++;
printf("%.*s: %d\n", n, str, pCrawl->counter);
}
for (int i = 0; i < ALPHABET_SIZE; i++) {
str[n] = INDEX_TO_CHAR(i);
setorder_rec(pCrawl->children[i], str, n + 1);
}
}
void setorder(trie_t *pTrie)
{
char tempword[40] = {0};
setorder_rec(pTrie->root, tempword, 0);
}
void insert(trie_t *pTrie, char key[])
{
int level;
int length = strlen(key);
int index;
trie_node_t *pCrawl;
pTrie->count++;
pCrawl = pTrie->root;
for( level = 0; level < length; level++ )
{
index = CHAR_TO_INDEX(key[level]);
if( !pCrawl->children[index] )
{
pCrawl->children[index] = getNode();
}
pCrawl = pCrawl->children[index];
}
pCrawl->counter++;
printf("counter slow 3= %d\n", pCrawl->counter);
}
int main()
{
char keys[][20] = {"THE", "THE", "BYE", "A", "THERE", "ANSWER", "ANSWER", "BBUWNTSMFK", "THE", "THEIR", "ANSWER", "THE", "LOL", "OMG", "WTF"};
trie_t trie;
char output[][20] = {"Not present in trie", "Present in trie"};
initialize(&trie);
// Construct trie
for(int i = 0; i < ARRAY_SIZE(keys); i++)
{
insert(&trie, keys[i]);
}
setorder(&trie);
for(int i=0; i<=9; i++)
{
printf("#%d %s=%d\n", i, words[i], counters[i]);
}
return 0;
}
我要排序的数组是“单词”和“计数器”
答案 0 :(得分:3)
以下是您可以使用的简单冒泡排序代码:
for (c = 0 ; c < ( n - 1 ); c++)
{
for (d = 0 ; d < n - c - 1; d++)
{
if (counters[d] > counters[d+1])
{
swap = counters[d];
counters[d] = counters[d+1];
counters[d+1] = swap;
swap2 = words[d];
words[d] = words[d+1];
words[d+1] = swap2;
}
}
}
printf("Sorted words:\n");
for ( c = 0 ; c < n ; c++ )
printf("%d\n", words[c]);**strong text**