Сортировка класса ArrayList особым способом - C#
Формулировка задачи:
Листинг программы
- using System;
- using System.Collections;
- using System.Collections.Generic;
- using System.IO;
- using System.Linq;
- using System.Text;
- using System.Threading.Tasks;
- namespace Nomatter
- {
- class Program
- {
- static void Main(string[] args)
- {
- string temp;
- bool done=false;
- StreamReader inp = new StreamReader("C:\\Learning and stuff\\Input_N.txt",Encoding.Default);
- temp = inp.ReadLine();
- int num = Convert.ToInt32(temp);
- ArrayList A = new ArrayList();
- string New_Klichka;
- for(int i=0;i<num;++i)
- {
- Sobaka temp_el = new Sobaka();
- temp_el.Klichka= inp.ReadLine();
- temp_el.Poroda = inp.ReadLine();
- temp_el.Pol = inp.ReadLine();
- temp_el.Vozrast =Convert.ToInt32( inp.ReadLine());
- temp_el.Medalei =Convert.ToInt32( inp.ReadLine());
- A.Add(temp_el);
- }
- PrintValues(A);
- Console.WriteLine("После сортировки:");
- A.Sort();
- PrintValues(A);
- Console.WriteLine("Введите имя искомой собаки:");
- New_Klichka = Console.ReadLine();
- for (int i = 0, j = num; i <=j &&!done; )
- {
- int ind = i + j / 2;
- Sobaka temp1 = A[ind] as Sobaka;
- switch( temp1.Klichka.CompareTo(New_Klichka))
- {
- case -1:
- i = j / 2;
- break;
- case 0:
- PrintSobaka(temp1);
- done = true;
- break;
- case 1:
- j = j / 2;
- break;
- }
- }
- if (!done)
- Console.WriteLine("Этой собаки нет в списке");
- Console.ReadKey();
- }
- private static void PrintSobaka(Sobaka B)
- {
- Console.Write(" {0}", B.Klichka.PadRight(10));
- Console.Write(" {0}", B.Poroda.PadRight(10));
- Console.Write(" {0}", B.Pol.PadRight(10));
- Console.Write(" {0}", B.Vozrast);
- Console.WriteLine(" {0}", B.Medalei);
- }
- private static void PrintValues(ArrayList A)
- {
- foreach(Sobaka B in A)
- PrintSobaka(B);
- }
- }
- }
- class Sobaka:IComparable
- {
- public string Klichka;
- public string Poroda;
- public string Pol;
- public int Vozrast;
- public int Medalei;
- public int CompareTo(object field)
- {
- Sobaka otherSobaka = field as Sobaka;
- if (otherSobaka != null)
- {
- int res = this.Klichka.CompareTo(otherSobaka.Klichka);
- if (res != 0)
- return res;
- else return this.Klichka.CompareTo(otherSobaka.Vozrast);
- }
- else throw new ArgumentException("Сравниваемое не является объектом класса Sobaka");
- }
- }
Решение задачи: «Сортировка класса ArrayList особым способом»
textual
Листинг программы
- public void InsertionSort(Sobaka[] array, IComparer<Sobaka> comparer)
- {
- for (int i = 1; i < array.Length; i++)
- {
- Sobaka cur = array[i];
- int j = i;
- while (j > 0 && comparer.Compare(cur, array[j - 1]) < 0)
- {
- array[j] = array[j - 1];
- j--;
- }
- array[j] = cur;
- }
- }
ИИ поможет Вам:
- решить любую задачу по программированию
- объяснить код
- расставить комментарии в коде
- и т.д