我只是在C中堆积一个数组。但是在运行时它给我分段错误(核心转储)...我不知道我在哪里尝试访问未分配的内存!!
#include<stdio.h>
int n;
int left(i)
{
return (2*i);
}
int right(i)
{
return (2*i + 1);
}
void min_heap(int a[],int i)
{
int l=left(i);
int r=right(i);
int min;
if((l<=n)&&(a[l]<=a[i])&&(a[l]<=a[r]))
{
min=a[l];
a[i]=a[i]+a[l];
a[l]=a[i]-a[l];
a[i]=a[i]-a[l];
}
else if((r<=n)&&(a[r]<=a[i])&&(a[r]<=a[l]))
{
min=a[r];
a[i]=a[i]+a[r];
a[r]=a[i]-a[r];
a[i]=a[i]-a[r];
}
min_heap(a,min);
}
int main()
{
printf("The no is : ");
scanf("%d",&n);
int i,a[n+1];
for(i=1;i<=n;i++)
{
scanf("%d",&a[i]);
}
for(i=n/2;i>=1;i--)
{
min_heap(a,i);
}
for(i=1;i<=n;i++)
{
printf("%d",a[i]);
}
return 0;
}
答案 0 :(得分:0)
您在min_heap(a,i)
时致电i == n/2
。
在这种情况下,在min_heap()
内,对right()
的调用将生效:
(2 * (n/2) + 1)
当n
为偶数时,会产生n+1
的正确索引并且访问a[r]
(带r == n+1
)超出了您已分配的数组的末尾
我不确定这是否是你的段错误的原因;我猜可能还有其他问题。
您可能应该只使用调试器来完成运行。
答案 1 :(得分:0)
以下是Jon Bentley撰写的More Programming Pearls代码,作为C文件中的注释编写。完整代码与您无关;它是通用接口,如bsearch()
和qsort()
的接口,但这是用awk
编写的。
/*
** See Appendix 2 of Jon Bentley "More Programming Pearls".
** See also Column 14 of Jon Bentley "Programming Pearls, 2nd Edn".
** Note that MPP algorithms are in terms of an array indexed from 1.
** C, of course, indexes arrays from zero.
**
** 1-based identities.
** root = 1
** value(i) = x(i)
** leftchild(i) = 2*i
** rightchild(i) = 2*i+1
** parent(i) = i/2
** null(i) = (i < 1) or (i > n)
**
** 0-based identities.
** root = 0
** value(i) = x(i)
** leftchild(i) = 2*(i+1)-1 = 2*i+1
** rightchild(i) = 2*(i+1)+1-1 = leftchild(i)+1
** parent(i) = (i+1)/2-1
** null(i) = (i < 0) or (i >= n) # NB: i < 0 irrelevant for unsigned numbers
*/
/*
** function swap(i, j t) {
** # x[i] :=: x[j]
** t = x[i]
** x[i] = x[j]
** x[j] = t
** }
**
** function siftup(l, u, i, p) {
** # pre maxheap(l, u-1)
** # post maxheap(l, u)
** i = u
** while (1) {
** # maxheap(l, u) except between i and its parent
** if (i <= l) break
** p = int(i/2) # p = parent(i)
** if (x[p] >= x[i]) break
** swap(p, i)
** i = p
** }
** }
**
** function siftdown(l, u, i, c) {
** # pre maxheap(l+1, u)
** # post maxheap(l,u)
** i = l
** while (1) {
** # maxheap(l, u) except between i and its children
** c = 2*i # c = leftchild(i)
** if (c > u) break;
** if (c + 1 <= u && x[c+1] > x[c]) c++
** if (x[i] >= x[c]) break
** swap(c, i)
** i = c
** }
** }
**
** function hsort( i) {
** # post sorted(1, n)
** for (i = int(n/2); i >= 1; i--)
** siftdown(i, n)
** for (i = n; i >= 2; i--) {
** swap(1, i)
** siftdown(1, i-1)
** }
** }
*/
在代码中,正在排序的数组是x
,从1
索引到N
。