C++ Program to calculate Bitonicity of an Array


Given with an array of integers and the task is to calculate the bitonicity of a given array using a function.

Bitonicity of an array is −

  • Initialised to 0
  • Incremented to 1 when the next element is greater than the previous value
  • Decremented to 1 when the next element is lesser than the previous value

Example

Input-: arr[] = { 1,4,3,5,2,9,10,11}
Output-: Bitonicity of an array is : 3

Explanation −

  • Initialize bitonicity calculating variable let’s say temp with 0.
  • Start from the first element of an array which is 1. Now compare arr[i] and arr[i-1] i.e. compare 4 and 1 here 4 is greater than 1 thereby increment temp with 1. Similarly compare 4 and 3 since 3 is lesser than 4 decrement the value of temp.
  • Print the final value of temp which is 3

Approach used in the below program is as follows

  • Traverse all the elements of an array let’s say arr[n] where n is size of an array
  • If arr[i] > arr[i-1], than bitonicity = bitonicity + 1
  • If arr[i] < arr[i-1], than bitonicity = bitonicity – 1
  • If arr[i] = arr[i-1], than bitonicity = bitonicity (unchanged)

Algorithm

Start
Step 1-> Declare function to calculate bitonicity 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

Example

 Live Demo

#include <iostream>
using namespace std;
// calculate bitonicity
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;
}

Output

IF WE RUN THE ABOVE CODE IT WILL GENERATE FOLLOWING OUTPUT

Bitonicity of an array is : 3

Updated on: 18-Oct-2019

74 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements