【发布时间】:2013-11-25 10:57:18
【问题描述】:
使用以下代码,我试图创建一个数字数组,然后对它们进行排序。但是如果我设置了一个高数组大小(MAX),程序会在最后一个“随机”生成的数字处停止,并且根本不会继续进行排序。谁能帮我解决这个问题?
#include <stdio.h>
#define MAX 2000000
int a[MAX];
int rand_seed=10;
/* from K&R
- returns random number between 0 and 62000.*/
int rand();
int bubble_sort();
int main()
{
int i;
/* fill array */
for (i=0; i < MAX; i++)
{
a[i]=rand();
printf(">%d= %d\n", i, a[i]);
}
bubble_sort();
/* print sorted array */
printf("--------------------\n");
for (i=0; i < MAX; i++)
printf("%d\n",a[i]);
return 0;
}
int rand()
{
rand_seed = rand_seed * 1103515245 +12345;
return (unsigned int)(rand_seed / 65536) % 62000;
}
int bubble_sort(void)
{
int t, x, y;
/* bubble sort the array */
for (x=0; x < MAX-1; x++)
for (y=0; y < MAX-x-1; y++)
if (a[y] > a[y+1])
{
t=a[y];
a[y]=a[y+1];
a[y+1]=t;
}
return 0;
}
【问题讨论】:
-
使用动态数组怎么样?
-
如果您会阅读(繁体)中文,this 可能会对您有所帮助。
-
你需要bubble_sort()的返回类型??
-
由于您的数组是在文件范围内声明的,因此这很可能不是您的问题。可能不是一个好主意是使用
rand()的熟版本,而不仅仅是库函数。此外,前向声明的语法在现代 C 中更加具体。将(void)用于不接收参数的函数。
标签: c