Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Text;
- using System.Threading.Tasks;
- namespace задача_полиморф_2
- {
- class Program
- {
- public static void Main(string[] args)
- {
- string[] data = { "Hello", "World", "Sometime", "Brotherhood" };
- foreach (string s in data)
- {
- Console.Write(s + " ");
- }
- Console.WriteLine();
- IStringComparer comparer1 = new LengthComparer();
- IStringComparer comparer2 = new FirstCharComparer();
- InsertionSort(data, comparer1);
- foreach(string s in data)
- {
- Console.Write(s + " ");
- }
- Console.WriteLine();
- InsertionSort(data, comparer2);
- foreach (string s in data)
- {
- Console.Write(s + " ");
- }
- Console.ReadKey();
- //
- }
- public static void InsertionSort(string[] array, IStringComparer comparer)
- {
- for (int i = 1; i < array.Length; i++)
- {
- string cur = array[i];
- int j = i;
- while (j > 0 && comparer.Compare(cur, array[j - 1]) == -1)
- {
- array[j] = array[j - 1];
- j--;
- }
- array[j] = cur;
- }
- }
- }
- interface IStringComparer
- {
- /// <summary>
- /// Возвращает 1 если первая строка больше второй
- /// Возвращает 0 если строки равны
- /// Возвращает -1 если первая строка меньше второй
- /// </summary>
- /// <param name="a">Первая строка</param>
- /// <param name="b">Вторая строка</param>
- /// <returns></returns>
- int Compare(string a, string b);
- }
- class LengthComparer:IStringComparer
- {
- public int Compare(string a, string b)
- {
- int result=0;
- if (a.Length > b.Length)
- {
- result = 1;
- }
- else if (a.Length < b.Length)
- {
- result = -1;
- }
- return result;
- }
- }
- class FirstCharComparer : IStringComparer
- {
- public int Compare(string a, string b)
- {
- int result = String.Compare(a, b, true); ;
- return result;
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment