using
System;
using
System.Collections.Generic;
class
MainClass
{
public
static
void
Main(
string
[] args)
{
List<Pair<
int
,
int
>> vector =
new
List<Pair<
int
,
int
>>();
vector.Add(
new
Pair<
int
,
int
>(1, 20));
vector.Add(
new
Pair<
int
,
int
>(3, 42));
vector.Add(
new
Pair<
int
,
int
>(4, 36));
vector.Add(
new
Pair<
int
,
int
>(2, 80));
vector.Add(
new
Pair<
int
,
int
>(7, 50));
vector.Add(
new
Pair<
int
,
int
>(9, 20));
vector.Add(
new
Pair<
int
,
int
>(3, 29));
vector.Sort((p1, p2) => {
if
(!p1.GetKey().Equals(p2.GetKey()))
{
return
p1.GetKey().CompareTo(p2.GetKey());
}
else
{
return
p1.GetValue().CompareTo(p2.GetValue());
}
});
Console.WriteLine(
"KEY\tELEMENT"
);
foreach
(Pair<
int
,
int
> pair
in
vector)
{
Console.WriteLine(pair.GetKey() +
"\t"
+ pair.GetValue());
}
Console.WriteLine(
"Search for key 3 in vector"
);
if
(BinarySearch(vector,
new
Pair<
int
,
int
>(3, 0), Comparer<Pair<
int
,
int
>>.Create((p1, p2) => p1.GetKey().CompareTo(p2.GetKey()))) >= 0)
{
Console.WriteLine(
"Element found"
);
}
else
{
Console.WriteLine(
"Element not found"
);
}
}
static
int
BinarySearch(List<Pair<
int
,
int
>> list, Pair<
int
,
int
> key, IComparer<Pair<
int
,
int
>> comparer)
{
int
left = 0, right = list.Count - 1;
while
(left <= right)
{
int
mid = left + (right - left) / 2;
int
comparisonResult = comparer.Compare(list[mid], key);
if
(comparisonResult < 0)
left = mid + 1;
else
if
(comparisonResult > 0)
right = mid - 1;
else
return
mid;
}
return
-1;
}
}
class
Pair<K, V>
{
private
K key;
private
V value;
public
Pair(K key, V value)
{
this
.key = key;
this
.value = value;
}
public
K GetKey()
{
return
key;
}
public
V GetValue()
{
return
value;
}
}