Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
C# program to find common elements in three sorted arrays
Firstly, initialize 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 common elements in the three-sorted arrays, iterate through the arrays using a while loop and check the first array with a second and second array with the third −
while (i < one.Length && j < two.Length && k < three.Length) {
if (one[i] == two[j] && 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 to run the following code to find common elements in three sorted arrays.
using System;
class Demo {
static void commonElements(int []one, int []two, int []three) {
int i = 0, j = 0, k = 0;
while (i < one.Length && j < two.Length && k < three.Length) {
if (one[i] == two[j] && 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
Advertisements