CSharp · Console
using System;
using System.Collections.Generic;
List<int> a = new(){ 2,3,5,7,11 };
List<int> b = new(){ 1,2,3,4,5,6,7 };
Afficher(IntersectionEnsembliste(a, b));
Afficher(IntersectionEnsembliste(a, new List<int>()));
Afficher(IntersectionEnsembliste(new List<int>(), b));
static void Afficher<T>(IEnumerable<T> elems)
{
foreach(T e in elems)
Console.Write($"{e} ");
Console.WriteLine();
}
// précondition : a est triée
// précondition : b est triée
static List<T> IntersectionEnsembliste<T>(List<T> a, List<T> b)
where T : IComparable<T>
{
List<T> dest = new();
for(int ia = 0, ib = 0; ia != a.Count && ib != b.Count; )
{
int res = a[ia].CompareTo(b[ib]);
if(res < 0)
++ia;
else if (res > 0)
++ib;
else if(dest.Count == 0 || dest[dest.Count - 1].CompareTo(a[ia]) != 0)
{
dest.Add(a[ia]); // ou b[ib]
++ia; ++ib;
}
}
return dest;
}