2

我有一个包含 5 个元素的数组(1024,1025,1026,1027,1028)。如何检查这些元素是否按顺序排列。如果数组有偶数个元素,我也可以这样做。

4

4 回答 4

2

遍历数组并确保前一个成员(如果存在)等于当前的减号1

for (int i = 1; i < 5; i++) {
     if (arr[i - 1] != arr[i] - 1) {
          // It's not sequential.
          break;
     }
}
于 2013-02-05T06:30:57.693 回答
0

我会建议这个解决方案(如果说sequential你的意思是ordered):

#include <stdio.h>

int isArraySequential(int * array, int size) {
    int isAscendingFirst;
    int isAscendingCurrent;
    int isChangeFound = 0;
    int i;

    // arrays of length 0/1/2 are assumed to be sequential
    if (size < 3)
      return 1;

    for (i=1; i < size; i++) {
      // in case there is a change
      if (array[i] != array[i-1]) {
          isAscendingCurrent = (array[i] > array[i-1]);
          // on first change
          if (!isChangeFound) {
            isChangeFound = 1;
            isAscendingFirst = isAscendingCurrent;
          }
          // on subsequent changes
          else {
            if (isAscendingFirst != isAscendingCurrent)
              return 0;
          }
      }
    }

    return 1;
}

int main(){
  int array1[4] = {1, 1, 0, -1};
  int array2[4] = {2, 2, 2, 2};
  int array3[4] = {1, 2, 4, 3};

  printf("Is array1 sequential ? %d\n", isArraySequential(array1, 4));
  printf("Is array2 sequential ? %d\n", isArraySequential(array2, 4));
  printf("Is array3 sequential ? %d\n", isArraySequential(array3, 4));

  return 0;
}

因为通常顺序数组可以按ascendingORdescending顺序排列,必须考虑到这一点。还有一些极端情况——长度为 0/1/2 的数组总是连续的(我不确定长度为 0)。

编辑:我已经修复了第一个数组元素具有相同值的情况的代码。现在它应该可以正常工作了。

于 2013-02-05T07:30:39.133 回答
0

只需遍历数组:

bool is_sequence(int *arr, int size) 
{
    int i;

    for(i = 0; i < (size - 1); i++)
    {
        if((arr[i] + 1) != arr[i])
            /* array is not sequential */
            return false;
    }

    /* array is sequential */
    return true;
}

<...>
if(is_sequence(my_array, 5))
    printf("sequential!"
else
    printf("not sequential");
于 2013-02-05T06:32:07.893 回答
0

You should compare the two neighboring numbers and you have to do the same thing for many times. So, a loop is necessary. An easy programme is as followed.

#include<stdio.h>
int main()
{
    int a[5]={1024,1025,1026,1027,1028};
    int i,s;
    for(i=0;i<4;i=i+1)
    {
        if(a[i]+1 != a[i+1])
        {  s=-1; break; }
        else
        {  s=0; }
    }
    if(s=0)
    { printf("sequential."); }
    else
    { printf("not sequential."); }
}

I hope that my answer could help you. Thank you.

于 2013-02-05T06:51:14.530 回答