From 399056f0e87df2044e14e842a16d021fb3c57781 Mon Sep 17 00:00:00 2001 From: Ramprashanth Date: Sun, 31 Oct 2021 11:41:01 +0530 Subject: [PATCH] Added Answer 15 and 16 --- Answer15.cpp | 46 ++++++++++++++++++++++++++++++++++++++++++++++ Answer16.cpp | 46 ++++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 92 insertions(+) create mode 100644 Answer15.cpp create mode 100644 Answer16.cpp diff --git a/Answer15.cpp b/Answer15.cpp new file mode 100644 index 0000000..99280eb --- /dev/null +++ b/Answer15.cpp @@ -0,0 +1,46 @@ +// C++ program to find Majority +// element in an array +#include +using namespace std; + +// Function to find Majority element +// in an array +void findMajority(int arr[], int n) +{ + int maxCount = 0; + int index = -1; // sentinels + for (int i = 0; i < n; i++) { + int count = 0; + for (int j = 0; j < n; j++) { + if (arr[i] == arr[j]) + count++; + } + + // update maxCount if count of + // current element is greater + if (count > maxCount) { + maxCount = count; + index = i; + } + } + + // if maxCount is greater than n/2 + // return the corresponding element + if (maxCount > n / 2) + cout << arr[index] << endl; + + else + cout << "No Majority Element" << endl; +} + +// Driver code +int main() +{ + int arr[] = { 1, 1, 2, 1, 3, 5, 1 }; + int n = sizeof(arr) / sizeof(arr[0]); + + // Function calling + findMajority(arr, n); + + return 0; +} \ No newline at end of file diff --git a/Answer16.cpp b/Answer16.cpp new file mode 100644 index 0000000..68224e6 --- /dev/null +++ b/Answer16.cpp @@ -0,0 +1,46 @@ +// C++ program to find Majority +// element in an array +#include +using namespace std; + +// Function to find Majority element +// in an array +void findMajority(int arr[], int n) +{ + int maxCount = 0; + int index = -1; // sentinels + for (int i = 0; i < n; i++) { + int count = 0; + for (int j = 0; j < n; j++) { + if (arr[i] == arr[j]) + count++; + } + + // update maxCount if count of + // current element is greater + if (count > maxCount) { + maxCount = count; + index = i; + } + } + + // if maxCount is greater than n/3 + // return the corresponding element + if (maxCount > n / 3) + cout << arr[index] << endl; + + else + cout << "No Majority Element" << endl; +} + +// Driver code +int main() +{ + int arr[] = { 1, 1, 2, 1, 3, 5, 1 }; + int n = sizeof(arr) / sizeof(arr[0]); + + // Function calling + findMajority(arr, n); + + return 0; +} \ No newline at end of file