ขั้นแรก เริ่มต้นอาร์เรย์ที่จัดเรียงสามตัว -
int []one = {20, 35, 57, 70};
int []two = {9, 35, 57, 70, 92};
int []three = {25, 35, 55, 57, 67, 70}; ในการค้นหาองค์ประกอบทั่วไปในอาร์เรย์สามประเภท ให้วนซ้ำในอาร์เรย์โดยใช้ลูป while และตรวจสอบอาร์เรย์แรกด้วยอาร์เรย์ที่สองและอาร์เรย์ที่สองกับอาร์เรย์ที่สาม −
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++;
} ตัวอย่าง
คุณสามารถลองเรียกใช้โค้ดต่อไปนี้เพื่อค้นหาองค์ประกอบทั่วไปในอาร์เรย์ที่จัดเรียงสามแบบ
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);
}
} ผลลัพธ์
Common elements: 35 57 70