C ++程序来计算数组的双音度
给定一个整数数组,任务是使用一个函数计算给定数组的双音度。
数组的双音为-
初始化为0
当下一个元素大于上一个值时,递增为1
当下一个元素小于上一个值时减为1
示例
Input-: arr[] = { 1,4,3,5,2,9,10,11}
Output-: Bitonicity of an array is : 3解释-
初始化双音度计算变量,假设temp为0。
从数组的第一个元素为1开始。现在比较arr[i]和arr[i-1],即比较4和1,这里4大于1,从而使temp递增1。类似地比较4和3,因为3是小于4会减小temp的值。
打印temp的最终值为3
以下程序中使用的方法如下
遍历数组的所有元素,假设arr[n]其中n是数组的大小
如果arr[i]>arr[i-1],则重音=重音+1
如果arr[i]<arr[i-1],则比特数=比特数–1
如果arr[i]=arr[i-1],则bitonicity=bitonicity(不变)
算法
Start
Step 1-> Declare function to计算重音 of an array
int cal_bitonicity(int arr[], int n)
set int temp = 0
Loop For int i = 1 and i < n and i++
IF (arr[i] > arr[i - 1])
Increment temp++
End
Else IF (arr[i] < arr[i - 1])
Decrement temp—
End
return temp
step 2-> In main() declare int arr[] = { 1,4,3,5,2,9,10,11}
set int n = sizeof(arr) / sizeof(arr[0])
Call cal_bitonicity(arr, n)
Stop示例
#include <iostream>
using namespace std;
//计算重音
int cal_bitonicity(int arr[], int n) {
int temp = 0;
for (int i = 1; i < n; i++) {
if (arr[i] > arr[i - 1])
temp++;
else if (arr[i] < arr[i - 1])
temp--;
}
return temp;
}
int main() {
int arr[] = { 1,4,3,5,2,9,10,11};
int n = sizeof(arr) / sizeof(arr[0]);
cout<<"Bitonicity of an array is : " <<cal_bitonicity(arr, n);
return 0;
}输出结果
如果我们运行以上代码,它将在输出后产生
Bitonicity of an array is : 3