gpt4 book ai didi

c - 为什么这种快速排序不排序

转载 作者:太空宇宙 更新时间:2023-11-04 04:02:48 24 4
gpt4 key购买 nike

我有一个结构哈希表。我想使用快速排序算法对存储桶的内容进行排序,这是我尝试过的代码。结果哈希表桶内容根本没有排序。

#define BUCKETS 6000
#define BK_ENTRIES 1024
void q_sort(int,int,int);

typedef struct fpinfo
{
char fing_print[33];
}fpinfo;

q_sort 方法

void q_sort(int left, int right,int bk)
{
if(left>=right)
return ;
char l_hold[33], r_hold[33];
int pivot=left;
l_hold=hash_table[bk][left].fp;
r_hold=hash_table[bk][right].fp;
hash_table[bk][pivot].fp=hash_table[bk][left].fp;
while (left < right)
{
while ((strcmp(hash_table[bk][right].fp,hash_table[bk][pivot].fp)>=0) && (left < right))
right--;

if (left != right)
{
hash_table[bk][left].fp=hash_table[bk][right].fp;
left++;
}
while ((strcmp(hash_table[bk][left].fp,hash_table[bk][pivot].fp)<=0) && (left < right))
right--;

if (left != right)
{
hash_table[bk][right].fp= hash_table[bk][left].fp;
left++;
}

}
hash_table[bk][left].fp=hash_table[bk][pivot].fp;
hash_table[bk][pivot].fp=hash_table[bk][left].fp;
hash_table[bk][left].fp=l_hold;
hash_table[bk][right].fp=r_hold;

if ((strcmp(hash_table[bk][left].fp,hash_table[bk][pivot].fp)<=0))
q_sort(left, pivot-1,bk);
if ((strcmp(hash_table[bk][right].fp,hash_table[bk][pivot].fp)>0))
q_sort(pivot+1, right,bk);
}

这是我在main中的调用方式

fread(hash_table,sizeof(hash_table),1,htfile);


for(int j=0;j<BUCKETS;++j)
{

q_sort(0,BK_ENTRIES-1,j);
}

你可能会说代码太长了,但我不能再短了。

编辑:

这里是hash_table的声明

struct fpinfo hash_table[BUCKETS][BK_ENTRIES];

我已经用 c 库函数 qsort() 解决了我的问题。但如果你们中的任何人仍想调查这个问题,我已将其更新为您的建议。

最佳答案

我有一个解决方案。我刚刚使用了 qsort() 标准 C 函数。我已经包含了所有的源代码,以便所有像我这样的初学者可以更好地理解它。

编辑为 wildplasser 的 建议:

#include<iostream>
#include<stdio.h>

#define BUCKETS 6000
#define BK_ENTRIES 1024

int compare (const void * a, const void * b);
typedef struct fpinfo
{
unsigned long long offset;
unsigned long length;
char fp[33];

}fpinfo;
struct fpinfo hash_table[BUCKETS][BK_ENTRIES];
void main()
{
struct fpinfo e;
char fname[100];
printf("Enter source file name\n");
scanf(fname);
FILE *htfile,*f2;
htfile=fopen(fname,"r+b");

if (htfile != NULL)
{
fread(hash_table,sizeof(hash_table),1,htfile);
for(int j=0;j<BUCKETS;++j)
{
qsort(hash_table[j],BK_ENTRIES,sizeof(e),compare);
}
}
else
{
printf("Couldn't open source file");
exit(1);
}
f2=fopen("dest.txt","w+b");
if (f2 != NULL)
{
fwrite(hash_table,sizeof(hash_table),1,f2);
}
else
{
printf("Couldn't open destination file");
exit(1);
}
fclose(htfile);

fclose(f2);

}
int compare (const void * a, const void * b)
{
struct fpinfo *fpa=(struct fpinfo*)a;
struct fpinfo *fpb=(struct fpinfo*)b;
return strcmp(( char*)fpa->fp,( char*)fpb->fp);
}

关于c - 为什么这种快速排序不排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9805641/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com