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
WBOYforward
2023-09-12 11:17:021258browse

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};

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++;
}

Example

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

Live Demo

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);
   }
}

Output

Common elements: 35 57 70 

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!

Statement:
This article is reproduced at:tutorialspoint.com. If there is any infringement, please contact admin@php.cn delete