C语言,堆排序的代码运行显示“heapsort”: 找不到标识符,是什么问题?

唯一坚持的任性 2019-04-18 11:22:32
#include <stdio.h> #include<stdlib.h> #define N 14 typedef int KeyType; typedef int InfoType; typedef int SeqList; typedef struct { KeyType key; InfoType otherinfo; }RecType; void main() { int i,n; RecType R[N]; printf("请输入将要排序元素的个数:"); scanf("%d", &n); printf("\n"); for(i=0; i < n; i++) { printf("请输入第%d个数为:",i+1); scanf("%d",&R[i]); } printf("排序前的数据:\n"); //打印排序前的数据 for (int i = 0; i < n; i++) { printf("%d ",R[i]); } heapsort(R); printf("\n排序后的数据:\n"); //打印排序后的数据 for (i = 0;i < n;i++) printf("%d ",R[i]); printf("\n"); system("pause"); } void max_heapify(RecType R[],int k,int m) //用筛选法调整堆 { RecType t; int i,j,x; t=R[k]; x=R[k].key; i=k; j=2*i; while(j<=m) { if (j<m && R[j].key<R[j+1].key) j=j+1; if(x<R[j].key) { R[i]=R[j]; i=j; j=2*i; } else break; } R[i]=t; } void build_max_heap(RecType R[],int n) //建大根堆算法 { int i; for (i = n/2;i >= 1;i--) max_heapify(R,i,n); } void heapsort(RecType R[]) //堆排序的算法 { int i,n; build_max_heap(R,n); for (i = n;i >1;i--) { R[0] = R[1]; R[1] = R[i]; R[i] = R[0]; max_heapify(R,1,i-1); } }
...全文
127 2 打赏 收藏 转发到动态 举报
写回复
用AI写文章
2 条回复
切换为时间正序
请发表友善的回复…
发表回复
xian_wwq 2019-04-19
  • 打赏
  • 举报
回复
先声明后使用
或者把被调用函数放在调用函数之前
自信男孩 2019-04-19
  • 打赏
  • 举报
回复
#include <stdio.h>
#include<stdlib.h>

#define N 14
typedef int KeyType;
typedef int InfoType;
typedef int SeqList;

typedef struct
{
KeyType key;
InfoType otherinfo;
}RecType;

void build_max_heap(RecType R[],int n); //建大根堆算法
void heapsort(RecType R[], int n); //堆排序的算法
//void main()
int main()
{
int i,n;
RecType R[N];
printf("请输入将要排序元素的个数:");
scanf("%d", &n);
printf("\n");
for(i=0; i < n; i++)
{
printf("请输入第%d个数为:",i+1);
scanf("%d",&R[i].key);
scanf("%d",&R[i].otherinfo);
}
printf("排序前的数据:\n"); //打印排序前的数据
for (int i = 0; i < n; i++)
{
printf("%d ",R[i].key);
printf("%d ",R[i].otherinfo);
}
heapsort(R, n);
printf("\n排序后的数据:\n"); //打印排序后的数据
for (i = 0;i < n;i++) {
printf("%d ",R[i].key);
printf("%d ",R[i].otherinfo);
}
printf("\n");
system("pause");
}
void max_heapify(RecType R[],int k,int m) //用筛选法调整堆
{
RecType t;
int i,j,x;

t=R[k];
x=R[k].key;
i=k;
j=2*i;
while(j<=m)
{
if (j<m && R[j].key<R[j+1].key)
j=j+1;
if(x<R[j].key)
{
R[i]=R[j];
i=j;
j=2*i;
}
else
break;
}
R[i]=t;

}
void build_max_heap(RecType R[],int n) //建大根堆算法
{
int i;

for (i = n/2;i >= 1;i--)
max_heapify(R,i,n);
}

void heapsort(RecType R[], int n) //堆排序的算法
{

//int i,n;
int i;

build_max_heap(R,n);
for (i = n;i >1;i--)
{
R[0] = R[1];
R[1] = R[i];
R[i] = R[0];
max_heapify(R,1,i-1);
}
}

供参考!

解决了大部分问题,但是你的算法有问题(为仔细看,没有解决),建议你还是在梳理一下算法
但从这个error描述来讲,就是没有在调用前声明该函数导致的。把函数声明放到main函数前就可以了。
但是有个其他问题,你见过scanf输入一个结构体的吗?

heapsort中n是局部变量,并且是一个随机值,直接传到build_max_heap(R,n);里,肯定会导致越界。

69,371

社区成员

发帖
与我相关
我的任务
社区描述
C语言相关问题讨论
社区管理员
  • C语言
  • 花神庙码农
  • 架构师李肯
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧