📜  intersection.cpp - C++ (1)

📅  最后修改于: 2023-12-03 15:01:25.681000             🧑  作者: Mango

Intersection.cpp - C++

Introduction

Intersection.cpp is a C++ program that finds the intersection of two sorted arrays. It uses a two-pointer approach to iterate through the arrays and compare their elements. The program is useful in a variety of applications such as data analysis, statistics, and machine learning.

Features
  • Efficiently finds the intersection of two sorted arrays
  • Returns the common elements as an array
  • Can handle arrays of any size
Usage

To use the Intersection.cpp program, first ensure that you have a C++ compiler installed on your machine. Then, download the Intersection.cpp file and compile it using the following command:

g++ Intersection.cpp -o Intersection

Next, create two sorted arrays and pass them as arguments to the program:

int arr1[] = {1, 2, 3, 4, 5};
int arr2[] = {3, 4, 5, 6, 7};

int m = sizeof(arr1) / sizeof(arr1[0]);
int n = sizeof(arr2) / sizeof(arr2[0]);

int* result = intersection(arr1, arr2, m, n);

for (int i = 0; i < sizeof(result) / sizeof(result[0]); i++) {
    cout << result[i] << " ";
}

This will output the common elements between the two arrays:

3 4 5
Code
#include <iostream>

using namespace std;

int* intersection(int arr1[], int arr2[], int m, int n) {
    int i = 0, j = 0, k = 0;
    int* result = new int[min(m, n)];

    while (i < m && j < n) {
        if (arr1[i] < arr2[j]) {
            i++;
        } else if (arr1[i] > arr2[j]) {
            j++;
        } else {
            result[k] = arr1[i];
            i++;
            j++;
            k++;
        }
    }

    return result;
}
Conclusion

Intersection.cpp is a powerful tool for finding the common elements between two sorted arrays. It is an efficient and easy-to-use program that can be applied in a multitude of contexts.