2017-07-14 83 views
-4

我在C中有一个简单的函数来获取数组是否已排序,但我似乎每次都得到不同的值。有时候我会通过3次测试,有时候会有2次测试通过,我不确定问题出在哪里。C:每次运行程序都会有不同的值

int is_sorted(int a[], int n) 
{ 
    for(int i = 0; i < n; i++) 
    { 
     if(a[i] > a[i + 1]) 
     { 
      return 0; 
     } 
    } 
    return 1; 
} 

int main() 
{ 
    int a[] = {2, 4, 9, 8, 12}; 
    int b[] = {-5, -2, 0, 8, 11, 15}; 
    int aa[] = {2, 18, 12, 9, 1, 2, 8, 11, 16, 3}; 
    int c[] = {4, 6, 8, 10}; 

    npassed = 0; 
    if(!is_sorted(a, 5)) 
    { 
     npassed++; 
    } 
    if(is_sorted(b, 6)) 
    { 
     npassed++; 
    } 
    if(!is_sorted(aa, 10)) 
    { 
     npassed++; 
    } 
    if(is_sorted(c, 5)) 
    { 
     npassed++; 
    } 
    printf("number passed is_sorted : %i\n", npassed); 
} 
+2

'if(a [i]> a [i + 1])'可能会超过数组的末尾 –

+2

它肯定会在这种情况下过去:'is_sorted(c,5)' – babon

+1

也被忽略'声明? –

回答

1

你的函数接受两个参数:

  • a:数组
  • n:数组大小

检查如果是排序您遍历所有元素,看看如果它的下一个元素比自己大。要做到这一点,您需要从零(可能的最低索引)到n-1(最高可能的索引)的数量为i
但是你总是检查i是否大于i+1。如果你达到i的最后可能的指数会发生什么?那么i+1等于n,因此在阵列之外。你阵列之外的是随机数据。

相关问题