判断一个数组是否为有序数组
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<assert.h>
bool Monoton(int* br, int n)
{
assert(br != nullptr && n > 1);
bool a = 0;
int sum = 0;
bool tmp = 0;
for (int i = 0; i < n - 1; ++i)
{
if (br[i + 1] != br[i])
{
tmp = br[i + 1] / br[i];
}
sum += tmp;
}
if (sum == 0 || sum == n - 1)
{
a = 1;
}
return a;
}
int main()
{
const int n = 10;
int ar[n] = { 100,90,89,78,78,56,45,34,23,12 };
bool a = 0;
a = Monoton(ar, n);
if (a)
{
printf("The sequence is monotone!\n");
}
else
{
printf("The sequence isn't monotone!\n");
}
return 0;
}
如果为有序数组,则数组中某个数除以下一个数,总大于等于1(如果为递增数列,则总小于等于1)。
令两数相除的结果赋值给bool型,递增数列全为0,递减数列全为1。