Computer >> 컴퓨터 >  >> 프로그램 작성 >> C++

배열의 Bitonicity를 계산하는 C++ 프로그램

<시간/>

정수 배열과 함께 주어진 작업은 함수를 사용하여 주어진 배열의 bitonicity를 계산하는 것입니다.

배열의 Bitonicity는 -

  • 0으로 초기화됨
  • 다음 요소가 이전 값보다 크면 1로 증가
  • 다음 요소가 이전 값보다 작으면 1로 감소

예시

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

설명 -

  • 0으로 temp를 가정하여 bitonicity 계산 변수를 초기화합니다.
  • 배열의 첫 번째 요소인 1부터 시작합니다. 이제 arr[i]와 arr[i-1]을 비교합니다. 즉, 4와 1을 비교합니다. 여기서 4는 1보다 크므로 temp를 1로 증가시킵니다. 마찬가지로 4와 3을 비교합니다. 3은 4보다 작기 때문에 temp 값을 감소시킵니다.
  • 3인 temp의 최종 값을 출력합니다.

아래 프로그램에서 사용된 접근 방식은 다음과 같습니다.

  • 배열의 모든 요소를 ​​순회한다고 가정해 봅시다. arr[n] 여기서 n은 배열의 크기입니다.
  • arr[i]> arr[i-1]이면 bitonicity =bitonicity + 1보다
  • arr[i]
  • arr[i] =arr[i-1]이면 bitonicity =bitonicity(변경되지 않음)보다

알고리즘

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

예시

#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;
}

출력

위의 코드를 실행하면 다음 출력이 생성됩니다.

Bitonicity of an array is : 3