ด้วยอาร์เรย์ของจำนวนเต็มและภารกิจคือการคำนวณ bitonicity ของอาร์เรย์ที่กำหนดโดยใช้ฟังก์ชัน
บิตโทนิซิตี้ของอาร์เรย์คือ −
- เริ่มต้นเป็น 0
- เพิ่มขึ้นเป็น 1 เมื่อองค์ประกอบถัดไปมากกว่าค่าก่อนหน้า
- ลดลงเหลือ 1 เมื่อองค์ประกอบถัดไปน้อยกว่าค่าก่อนหน้า
ตัวอย่าง
Input-: arr[] = { 1,4,3,5,2,9,10,11}
Output-: Bitonicity of an array is : 3 คำอธิบาย −
- เริ่มต้นตัวแปรการคำนวณ bitonicity สมมุติว่า temp เป็น 0
- เริ่มจากองค์ประกอบแรกของอาร์เรย์ซึ่งก็คือ 1 ตอนนี้เปรียบเทียบ arr[i] และ arr[i-1] เช่น เปรียบเทียบ 4 กับ 1 ที่นี่ 4 มากกว่า 1 ดังนั้นจึงเพิ่มอุณหภูมิด้วย 1 เปรียบเทียบ 4 และ 3 ในทำนองเดียวกัน เนื่องจาก 3 มีค่าน้อยกว่า 4 ทำให้ค่าอุณหภูมิลดลง
- พิมพ์ค่าสุดท้ายของ temp ซึ่งเท่ากับ 3
แนวทางที่ใช้ในโปรแกรมด้านล่างมีดังนี้
- สำรวจองค์ประกอบทั้งหมดของอาร์เรย์ สมมติว่า 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