Home > Backend Development > C#.Net Tutorial > C# program to find common elements in three sorted arrays

C# program to find common elements in three sorted arrays

WBOY
Release: 2023-09-12 11:17:02
forward
1227 people have browsed it

C# 程序在三个排序数组中查找公共元素

First, initialize the three sorted arrays -

int []one = {20, 35, 57, 70};
int []two = {9, 35, 57, 70, 92};
int []three = {25, 35, 55, 57, 67, 70};
Copy after login

To find the common elements in the three sorted arrays, use a while loop to iterate the array and use the Two arrays to check the first array and a third array to check the second array -

while (i < one.Length &amp;&amp; j < two.Length &amp;&amp; k < three.Length) {
   if (one[i] == two[j] &amp;&amp; two[j] == three[k]) {
      Console.Write(one[i] + " ");
      i++;j++;k++;
   }
   else if (one[i] < two[j])
      i++;
   else if (two[j] < three[k])
      j++;
   else
      k++;
}
Copy after login

Example

You can try running the following code to find common elements in three sorted arrays .

Live Demo< /p>

using System;
class Demo {
   static void commonElements(int []one, int []two, int []three) {
      int i = 0, j = 0, k = 0;
      while (i < one.Length &amp;&amp; j < two.Length &amp;&amp; k < three.Length) {
         if (one[i] == two[j] &amp;&amp; two[j] == three[k]) {
            Console.Write(one[i] + " ");
            i++;j++;k++;
         }
         else if (one[i] < two[j])
            i++;
         else if (two[j] < three[k])
            j++;
         else
            k++;
      }
   }
   public static void Main() {
      int []one = {20, 35, 57, 70};
      int []two = {9, 35, 57, 70, 92};
      int []three = {25, 35, 55, 57, 67, 70};

      Console.Write("Common elements: ");

      commonElements(one, two, three);
   }
}
Copy after login

Output

Common elements: 35 57 70 
Copy after login

The above is the detailed content of C# program to find common elements in three sorted arrays. For more information, please follow other related articles on the PHP Chinese website!

source:tutorialspoint.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template