LinuxSir.cn,穿越时空的Linuxsir!

 找回密码
 注册
搜索
热搜: shell linux mysql
查看: 876|回复: 4

[求助]一小段源码中的奇遇

[复制链接]
发表于 2005-5-25 23:53:25 | 显示全部楼层 |阅读模式

  1. #include <stdio.h>

  2. //#define DIM 7
  3. #define DIM 14

  4. int main()
  5. {
  6.         //int array[DIM] = {44,55,12,42,94,13,57};
  7.         int array[DIM] = {29, 27, 38, 23, 0, 24, 26, 28, 25, 33, 52, 40, 43, 36};
  8.         int index;
  9.         int i;
  10.         int temp;
  11.         int flag = 1;/*1 means sorting is needed, 0 means otherwise.*/
  12.         printf("The original array is:\n");
  13.         for (i=0; i<=DIM-1; i++)
  14.                 printf("%d ", array[i]);
  15.         putchar('\n');

  16.         for (index=DIM-1; index>=1 && flag; index--) {
  17.                 /*'index' means to which array element should the search for the largest be carried out*/
  18.                 /*the last search deals with only two elements, thus 'index' is 1 at that time*/
  19.                 flag=0;
  20.                 for (i=0; i<=index; i++) {
  21.                         if (array[i] > array[i+1]) {
  22.                                 temp = array[i+1];
  23.                                 array[i+1] = array[i];
  24.                                 array[i] = temp;
  25.                                 flag = 1;
  26.                         }
  27.                 }
  28.         }
  29.         for (i=0; i<=DIM-1; i++)
  30.                 printf("%d ", array[i]);
  31.         putchar('\n');
  32. }

复制代码


作冒泡算法实验的。如果用7 个元素,输出正常;用14个元素,输出就有问题。
:confused:
发表于 2005-5-26 00:55:36 | 显示全部楼层
if (array > array[i+1]) {

其中(i+1)可能是14
回复 支持 反对

使用道具 举报

发表于 2005-5-26 01:01:21 | 显示全部楼层
for (i=0; i<index; i++)
i 不能 <=index
否则的话 判断到最后一个 array[i+1] ,下标越界
回复 支持 反对

使用道具 举报

 楼主| 发表于 2005-5-26 08:39:13 | 显示全部楼层
Post by mars_diy
for (i=0; i<index; i++)
i 不能 <=index
否则的话 判断到最后一个 array[i+1] ,下标越界


可是我原来用7个元素就没问题,我还以为代码没问题呢。后来随便换了个14元素的,就...
回复 支持 反对

使用道具 举报

发表于 2005-5-26 22:10:02 | 显示全部楼层
7个元素的时候正确运行只是碰巧而已,取决于array[8]的大小,如果比array[7]大就没事,否则就出错了。。。
回复 支持 反对

使用道具 举报

您需要登录后才可以回帖 登录 | 注册

本版积分规则

快速回复 返回顶部 返回列表