Algorithms and their C++ Implementations
1. Frequency of Occurrence of All Numbers in an Array
Description:
This program calculates the frequency of each number in a given array.
C++ Code:
#include <iostream>
using namespace std;
void frequency(int arr[], int n) {
int count[1000] = {0}; // Assuming maximum number is less than 1000
for (int i = 0; i < n; i++) {
count[arr[i]]++;
for (int i = 0; i < 1000; i++) {
if (count[i] > 0) {
cout << i << " occurs " << count[i] << " times." << endl;
int main() {
int arr[] = {1, 2, 2, 3, 3, 3, 4};
int n = sizeof(arr) / sizeof(arr[0]);
frequency(arr, n);
return 0;
2. BFS and DFS
Description:
Breadth-First Search (BFS) and Depth-First Search (DFS) are algorithms used to traverse or search
graph structures.
C++ Code for BFS:
#include <iostream>
using namespace std;
void bfs(int graph[5][5], int start, int n) {
bool visited[5] = {false};
int queue[5], front = 0, rear = 0;
visited[start] = true;
queue[rear++] = start;
cout << "BFS Traversal: ";
while (front < rear) {
int node = queue[front++];
cout << node << " ";
for (int i = 0; i < n; i++) {
if (graph[node][i] == 1 && !visited[i]) {
visited[i] = true;
queue[rear++] = i;
}