Реализовать бинарный поиск для переопределенного компаратора - C#
Формулировка задачи:
Добрый день, такая проблема: Не могу понять как мне реализовать бинарный поиск для моего переопределенного компаратора. Суть задачи: написать линейный поиск и проверить встроенным бинарным. Вот с бинарным то и проблемы. Коллекция ArrayList.
Листинг программы
- using System;
- using System.Collections;
- using System.Linq;
- using System.Text;
- using System.IO;
- using System.Threading.Tasks;
- namespace ConsoleApplication1
- {
- public class Student : IComparable
- {
- /* Переопределяем стандартный метод CompareTo интерфейса IComparable,
- нужный для вызова метода Sort */
- public int CompareTo(Object rhs)
- {
- Student r = (Student)rhs;
- Int32 ret = this.Name.CompareTo(r.Name);
- if (ret == 0)
- {
- ret = this.Surname.CompareTo(r.Name);
- }
- if (ret == 0)
- {
- ret = this.FatherName.CompareTo(r.FatherName);
- }
- if (ret == 0)
- {
- ret = this.gruppa.CompareTo(r.gruppa);
- }
- return ret;
- }
- //обьявление членов класса
- public string Name;
- public string Surname;
- public string FatherName;
- public int Age;
- public string Pol;
- public double Rez1;
- public double Rez2;
- public double Rez3;
- public int gruppa;
- }
- public class Sort
- {
- static StreamReader read; //поток для чтения
- static int NumberLines()
- {
- int kol = 0;
- String line;
- while ((line = read.ReadLine()) != null)
- {
- kol++;
- }
- read.Close();
- return kol;
- }
- static void ReadFile(Student[] a)
- {
- char[] delimiters = { ' ' };
- string strfromfile = read.ReadLine();
- string[] line = new string[9];
- int i = 0;
- while (strfromfile != null)
- {
- a[i] = new Student();
- line = strfromfile.Split(delimiters);
- a[i].Name = line[0];
- a[i].Surname = line[1];
- a[i].FatherName = line[2];
- a[i].Age = Convert.ToInt32(line[3]);
- a[i].Pol = line[4];
- a[i].Rez1 = Convert.ToDouble(line[5]);
- a[i].Rez2 = Convert.ToDouble(line[6]);
- a[i].Rez3 = Convert.ToDouble(line[7]);
- a[i].gruppa = Convert.ToInt32(line[8]);
- i++;
- strfromfile = read.ReadLine();
- }
- read.Close();
- }
- static void Output(Student[] a)
- {
- foreach (Student i in a)
- {
- Console.Write("{0} {1} {2} {3} {4} {5} {6} {7} {8}\n", i.Name, i.Surname, i.FatherName, i.Age, i.Pol, i.Rez1, i.Rez2, i.Rez3, i.gruppa);
- }
- }
- static void AddtoArrayList(Student[] a, int n)
- {
- ArrayList win = new ArrayList();
- for (int i = 0; i < n; i++)
- {
- win.Add(a[i]);
- }
- Console.WriteLine("Сортировка ArrayList.Sort()\n");
- win.Sort();
- //вывод элементов отсортированного массива - доступ к нему как к коллекции
- foreach (Student i in win)
- {
- Console.Write("{0} {1} {2} {3} {4} {5} {6} {7} {8}\n", i.Name, i.Surname, i.FatherName, i.Age, i.Pol, i.Rez1, i.Rez2, i.Rez3, i.gruppa);
- }
- //Сортировка Шелла
- }
- static void Shell(Student[] a, int n)
- {
- int step = n / 2;
- while (step > 0)//пока шаг не 0
- {
- for (int i = 0; i < (n - step); i++)
- {
- int j = i;
- //будем идти начиная с i-го элемента
- while (j >= 0 && a[j].CompareTo(a[j + step]) == 1)
- //пока не пришли к началу массива
- //и пока рассматриваемый элемент больше
- //чем элемент находящийся на расстоянии шага
- {
- //меняем их местами
- Student temp = a[j];
- a[j] = a[j + step];
- a[j + step] = temp;
- j--;
- }
- }
- step = step / 2;//уменьшаем шаг
- }
- Console.Write("\nСортировка Шелла\n\n");
- Output(a);
- }
- static void LinearSearch(Student[] a, int n)
- {
- Console.WriteLine("\nЛинейный поиск:\nЧто найти?");
- string p = Console.ReadLine();
- for (int i = 0; i < n; i++)
- {
- string fullName = a[i].Name + " " + a[i].Surname + " " + a[i].FatherName;
- if (p == fullName)
- {
- Console.Write(i);
- }
- }
- }
- /* static void BinarySrch(Student[] a, int n)
- {
- ArrayList win = new ArrayList();
- for (int i = 0; i < n; i++)
- {
- win.Add(a[i]);
- }
- win.Sort();
- Console.WriteLine("Двоичный поиск:\nчто ищем?");
- string str = Console.ReadLine();
- Console.WriteLine(win.BinarySearch(str));
- }*/
- static void Main(string[] args)
- {
- read = new StreamReader("D:\\i.txt");
- int kol = NumberLines();
- Student[] a = new Student[kol];
- read = new StreamReader("D:\\i.txt");
- ReadFile(a);
- AddtoArrayList(a, kol);
- Shell(a, kol);
- LinearSearch(a, kol);
- // BinarySrch(a,kol);
- Console.ReadKey();
- }
- }
- }
Решение задачи: «Реализовать бинарный поиск для переопределенного компаратора»
textual
Листинг программы
- public class Student : IComparable
- {
- /* Переопределяем стандартный метод CompareTo интерфейса IComparable,
- нужный для вызова метода Sort */
- public int CompareTo (Object ro)
- {
- Student r = ro as Student;
- if (r == null)
- return 1;
- int ret = Name.CompareTo (r.Name);
- if (ret != 0)
- return ret;
- ret = Surname.CompareTo (r.Surname);
- if (ret != 0)
- return ret;
- ret = FatherName.CompareTo (r.FatherName);
- if (ret != 0)
- return ret;
- return gruppa.CompareTo (r.gruppa);
- }
- //обьявление членов класса
- public string Name;
- public string Surname;
- public string FatherName;
- public int Age;
- public string Pol;
- public double Rez1;
- public double Rez2;
- public double Rez3;
- public int gruppa;
- public override string ToString ()
- {
- return string.Format ("[Student: Name={0}, Surname={1}, FatherName={2}, gruppa={3}]", Name, Surname, FatherName, gruppa);
- }
- }
- static void Main (string[] args)
- {
- ArrayList l = new ArrayList ();
- l.Add (new Student () {Name = "Иван", FatherName = "Петрович", Surname = "Козлов", gruppa = 1});
- l.Add (new Student () {Name = "Иван", FatherName = "Иванович", Surname = "Агафонов", gruppa = 1});
- l.Sort ();
- Console.WriteLine (String.Join ("\n", l.ToArray()));
- }
ИИ поможет Вам:
- решить любую задачу по программированию
- объяснить код
- расставить комментарии в коде
- и т.д