Алгоритм поиска - C# (181953)
Формулировка задачи:
Есть код. Сортирует Собак по кличкам и выполняет поиск по ним же.
Нужно переделать чтобы был поиск по породе. Никак не могу понять как.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections;
using System.IO;
namespace ConsoleApplication1
{
class Program
{
public class mySort : IComparer
{
int IComparer.Compare(Object x, Object y)
{
Dog r = (Dog)x;
Dog q = (Dog)y;
Int32 ret = r.name.CompareTo(q.name); //менять где .name на то что нужно(.age, .poroda)
if (ret == 0)
{
return r.name.CompareTo(q.name); //тоже
}
else
{ return ret; }
}
}
public class Dog : IComparable
{
public string name;
public string poroda;
public string pol;
public int age;
public int medal;
public int CompareTo(Object rhs)
{
Dog r = (Dog)rhs;
Int32 ret = this.name.CompareTo(r.name);// тожже
return ret;
}
}
static void read(ArrayList DOG, string filename)
{
Encoding enc = Encoding.GetEncoding(1251);
StreamReader file = new StreamReader(filename, enc);
while (true)
{
string st = file.ReadLine();
if (st == null) break;
string[] b = st.Split();
Dog a = new Dog();
a.name = b[0];
a.poroda = b[1];
a.pol = b[2];
a.age = int.Parse(b[3]);
a.medal = int.Parse(b[4]);
DOG.Add(a);
}
file.Close();
}
static void Main(string[] args)
{
ArrayList DOG = new ArrayList();
read(DOG, "dogs.txt");
Console.WriteLine("\n");
IComparer abc = new mySort();
DOG.Sort(abc);
Console.WriteLine("Сортировка по Кличке");
foreach (Dog i in DOG)
{
Console.WriteLine(" {0} \t {1} \t {2} \t {3} \t {4}", i.name, i.poroda, i.pol, i.age, i.medal);
}
Console.WriteLine("\n");
Console.WriteLine("Кого будем искать? \n");
string l = Console.ReadLine();
Dog q = new Dog();
q.name = l; // и здесь
object obj = q;
int retVal = DOG.BinarySearch(obj);
if (retVal >= 0)
{
Dog a = new Dog();
a=(Dog)DOG[retVal];
Console.WriteLine(" {0} \t {1} \t {2} \t {3} \t {4}", a.name, a.poroda, a.pol, a.age, a.medal);
}
else
{
Console.Write("No results");
}
Console.ReadLine();
}
}
}Решение задачи: «Алгоритм поиска»
textual
Листинг программы
Console.WriteLine("\n");
Console.WriteLine("Кого будем искать? \n");
string l = Console.ReadLine();
Dog q = new Dog();
q.name = l; // и здесь
object obj = q;
int retVal = DOG.BinarySearch(obj);
if (retVal >= 0)
{
Dog a = new Dog();
a=(Dog)DOG[retVal];
Console.WriteLine(" {0} \t {1} \t {2} \t {3} \t {4}", a.name, a.poroda, a.pol, a.age, a.medal);
}
else
{
Console.Write("No results");
}