有人告诉我,对链表进行排序的最佳方法是将该链表复制到数组中并对该数组进行排序。从链表创建数组并对数组进行排序C
#define SIZE 7000
所以我的链接列表:
typedef struct no{
char *nome;
int count;
struct no * prox;
}*link;
我的数组:
typedef struct MyArray
{
char name[141];
int count;
}MyArray;
MeuArray v[SIZE];
现在我创建阵列功能:
void create_array()
{
link tmp = head;
int cont = 0;
int i;
while (tmp != NULL)
{
strcpy(v[cont].nome, tmp->nome);
v[cont].count = tmp->count;
tmp = tmp->prox;
cont++;
}
for (i = 0; i < SIZE; i++)
printf("%s %d\n", v[i].nome, v[i].count);
}
不知道这是正确的。 现在我不知道哪个是最好的/最快的。 qsort或其他。 如果快速排序:
int compare(struct MeuArray *elem1, struct MeuArray *elem2)
{
if (elem1->count < elem2->count)
return -1;
else if (elem1->count > elem2->count)
return 1;
else
{
if (strcmp(elem1->name, elem2->name) > 1)
return 1;
else
return -1;
}
}
我也试过这种方式(排序我的链接列表):
void insertionSort(link current)
{
link head = current;
link inserP = head;
current = current->prox;
while (current != NULL)
{
inserP = head;
while (inserP != current)
{
if (inserP->count > current->count)
{
int temp = current->count;
current->count = inserP->count;
inserP->count = temp;
}
else /* if (inserP->count < current->count) */
inserP = inserP->prox;
/*else
{
if (strcmp(inserP->name, current->name) > 0)
{
char temp2 = strcpy(temp2, current->name);
strcpy(current->name, inserP->name);
strcpy(inserP->name, temp2);
}
else
inserP = inserP->prox;
} */
}
}
current = current->prox;
}
有:
link head = NULL;
apreciated任何帮助。
编辑
我的qsort我希望被计数则首先比较的名字。 问题是我只能按数量排序。 如何按名称排序?
代码:
int compare (const void * a, const void * b)
{
MeuArray *MeuArrayA = (MeuArray *)a;
MeuArray *MeuArrayB = (MeuArray *)b;
if (MeuArrayB->count > MeuArrayA->count)
return 1;
else if (MeuArrayB->count < MeuArrayA->count)
return -1;
else
{
if (strcmp(MeuArrayB->nome, MeuArrayA->nome))
return 1;
else
return -1;
}
}
调试.................... .. –
链接列表的内容是什么?为什么它有一个计数变量? –
你的问题没有提出问题;-)你的问题是什么?代码是否产生错误或不正确的结果?你尝试过什么输入值? – siegi