#12.Journey to DSA in C++

#12.Journey to DSA in C++

ยท

5 min read

"Hey, it's Joyshree! ๐ŸŒŸ Ready to embark on a thrilling journey through the enchanting realm of Data Structures and Algorithms in C++? ๐Ÿš€ Imagine we're explorers, and DSA is our treasure map, guiding us through the magical forests of code and the intricate caves of problem-solving. Exploring the Naive Approach to Finding the Most Frequent Element in an Array with C++

Introduction

Welcome to another exciting blog post! Today, we're going to dive into a fundamental programming concept - finding the most frequent element in an array. But, we'll be doing it the old-fashioned way: using a naive approach in C++. No fancy libraries, no complex algorithms - just the basics.

Why a Naive Approach?

Before we start writing code, let's talk about the naive approach. It's called "naive" because it's straightforward. While it might not be the most efficient method, it's an excellent way to understand the core principles of problem-solving.

Here's the plan:

  1. Create an array with some elements.

  2. Initialize variables to keep track of the most frequent element and its count.

  3. Iterate through the array, comparing each element with the rest to find its frequency.

  4. Update our tracking variables when we find an element with a higher count.

  5. Return the most frequent element.

The C++ Program

Let's put our plan into action with a C++ program. Here's a sample code snippet that demonstrates the naive approach to find the most frequent element in an array.

#include <iostream>

int findMostFrequentElement(int arr[], int size) {
    int maxCount = 0;       // Initialize variables to keep track of the most frequent element.
    int mostFrequent = -1;

    for (int i = 0; i < size; i++) {
        int count = 0;      // Count the frequency of the current element.

        for (int j = 0; j < size; j++) {
            if (arr[i] == arr[j]) {
                count++;
            }
        }

        if (count > maxCount) {  // Update the tracking variables if we find a more frequent element.
            maxCount = count;
            mostFrequent = arr[i];
        }
    }

    return mostFrequent;  // Return the most frequent element.
}

int main() {
    int arr[] = {1, 2, 2, 3, 4, 2, 5, 2, 6};
    int size = sizeof(arr) / sizeof(arr[0]);
    int mostFrequentElement = findMostFrequentElement(arr, size);

    std::cout << "The most frequent element is: " << mostFrequentElement << std::endl;

    return 0;
}

let me break down the provided C++ program step by step and help you to understand easily,

#include <iostream>

In the first line, the necessary C++ library (iostream) is included, which is used for input and output operations.

int findMostFrequentElement(int arr[], int size) {

Here, a function named findMostFrequentElement is declared. This function takes two parameters: an integer array arr and an integer size representing the size of the array. The purpose of this function is to find and return the most frequently occurring element in the given array.

    int maxCount = 0;       // Initialize variables to keep track of the most frequent element.
    int mostFrequent = -1;

Inside the function, two variables are initialized: maxCount and mostFrequent. These variables are used to keep track of the element with the highest frequency (mostFrequent) and the count of its occurrences (maxCount).

    for (int i = 0; i < size; i++) {

A for loop is used to iterate through the array arr. The loop variable i is used to traverse the array elements.

        int count = 0;      // Count the frequency of the current element.

Inside the outer loop, a variable count is initialized to 0. This variable will be used to count the frequency of the current element (arr[i]) being examined.

        for (int j = 0; j < size; j++) {

Within the outer loop, there is another nested for loop. This loop, controlled by the variable j, iterates through the array again.

            if (arr[i] == arr[j]) {
                count++;
            }

In the inner loop, the program checks if the current element (arr[i]) is equal to the element at the index j. If they are equal, it increments the count variable, effectively counting how many times the current element appears in the array.

        if (count > maxCount) {  // Update the tracking variables if we find a more frequent element.
            maxCount = count;
            mostFrequent = arr[i];
        }
    }

After the inner loop finishes, it checks if the count variable (the frequency of the current element) is greater than the current maxCount (the maximum frequency found so far). If it is, it updates maxCount to the new count and updates mostFrequent to the element (arr[i]) with the higher frequency.

    return mostFrequent;  // Return the most frequent element.
}

The function returns the most frequently occurring element (mostFrequent) once the outer loop has finished iterating through the entire array.

Now, moving on to the main function:

int main() {
    int arr[] = {1, 2, 2, 3, 4, 2, 5, 2, 6};

In the main function, an integer array arr is initialized with values {1, 2, 2, 3, 4, 2, 5, 2, 6}.

    int size = sizeof(arr) / sizeof(arr[0]);

The size variable is calculated by dividing the total size of the array (sizeof(arr)) by the size of a single array element (sizeof(arr[0]) to determine the number of elements in the array.

    int mostFrequentElement = findMostFrequentElement(arr, size);

The findMostFrequentElement function is called with the arr and size as arguments, and the result (the most frequent element) is stored in the variable mostFrequentElement.

    std::cout << "The most frequent element is: " << mostFrequentElement << std::endl;

Finally, the program prints out the most frequent element found by the findMostFrequentElement function.

Conclusion:

The naive approach to finding the most frequent element in an array is a great starting point for beginners to understand basic problem-solving techniques. However, it's essential to note that this approach may not be the most efficient for large datasets. In real-world scenarios, more advanced algorithms are available for better performance.

In future blog posts, we'll explore more efficient ways to tackle this problem, so stay tuned. Until then, keep coding and keep learning!

ย