Как вычислить количество сравнений и перестановок? - C#

Узнай цену своей работы

Формулировка задачи:

Здравствуйте. У меня есть 2 сортировки "Вставкой" и Шейкером, как мне посчитать кол-во сравнений и перестановок в каждом из них.
Листинг программы
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. using System.Threading.Tasks;
  6. namespace ConsoleApp2
  7. {
  8. class Program
  9. {
  10. public int[] a = new int[50];
  11.  
  12. static void PoVozrostaniy(ref int[] a, int count)
  13. {
  14. {
  15. int i, j, t;
  16. Random rand = new Random();
  17. for (i = 0; i < 50; i++)
  18. a[i] = rand.Next(0, 400);
  19. for (i = 1; i < 50; i++)
  20. {
  21. t = a[i];
  22. for (j = i; j > 0 && a[j - 1] > t; j--)
  23. {
  24. a[j] = a[j - 1];
  25. }
  26. a[j] = t;
  27. }
  28. Console.WriteLine();
  29. Console.WriteLine("Сгенерированный массив по возрастанию:");
  30. for (j = 0; j < 50; j++)
  31. {
  32. Console.Write(a[j] + " ");
  33. }
  34. }
  35. }
  36.  
  37. static void PoUbivaniyu(ref int[] a, int count)
  38. { int i, j,t;
  39. Random rand = new Random();
  40. for (i=0;i<50;i++)
  41. a[i] = rand.Next(0, 400);
  42. for(i=1;i<50;i++)
  43. {
  44. t=a[i];
  45. for(j=i;j>0 && a[j-1]<t;j--)
  46. {
  47. a[j]=a[j-1];
  48. }
  49. a[j]=t;
  50. }
  51. Console.WriteLine();
  52. Console.WriteLine("Сгенерированный массив по спадонию:");
  53. for (j=0;j<50;j++)
  54. {
  55. Console.Write(a[j] + " ");
  56. }
  57. }
  58.  
  59. static void CreateMass(ref int[] a, int count)
  60. {
  61. Console.WriteLine("Сформированный массив:");
  62. Random rand = new Random();
  63. for (int i = 0; i < 50; i++)
  64. {
  65. a[i] = rand.Next(0, 400);
  66. Console.Write(a[i]+" ");
  67. }
  68. ;
  69. }
  70. static void SortInsertMethod(ref int[] a, int count)
  71. {
  72. int x, i, j;
  73. Console.WriteLine();
  74. Console.WriteLine("Отсортированный массив методом вставки:");
  75. for (i = 0; i < 50; i++)
  76. {
  77. x = a[i];
  78. for (j = i - 1; j >= 0 && a[j] > x; j--)
  79. {
  80. a[j + 1] = a[j];
  81. }
  82. a[j + 1] = x;
  83. }
  84. for (i = 0; i < 50; i++)
  85. { Console.Write(a[i] + " "); }
  86. Console.WriteLine();
  87. }
  88.  
  89. static void ShakeSort(ref int[] a, int count)
  90. {
  91. int b = 0;
  92. int left = 0;//Левая граница
  93. int right = 50 - 1;//Правая граница
  94. Console.WriteLine("Отсортированный массив методом Шейкера:");
  95. while (left < right)
  96. {
  97. for (int i = left; i < right; i++)//Слева направо...
  98. {
  99. if (a[i] > a[i + 1])
  100. {
  101. b = a[i];
  102. a[i] = a[i + 1];
  103. a[i + 1] = b;
  104. b = i;
  105. }
  106. }
  107. right = b;//Сохраним последнюю перестановку как границу
  108. if (left >= right) break;//Если границы сошлись выходим
  109. for (int i = right; i > left; i--)//Справа налево...
  110. {
  111. if (a[i - 1] > a[i])
  112. {
  113. b = a[i];
  114. a[i] = a[i - 1];
  115. a[i - 1] = b;
  116. b = i;
  117. }
  118. }
  119. left = b;//Сохраним последнюю перестановку как границу
  120. }
  121. for (int i = 0; i < 50; i++)
  122. { Console.Write(a[i] + " "); }
  123. Console.WriteLine();
  124. }
  125.  
  126. static void Main(string[] args)
  127. {
  128. int k ;
  129. k = int.Parse( Console.ReadLine());
  130.  
  131. int[] a = new int[50];
  132. //Program prog = new Program();
  133. if (k == 1)
  134. {
  135. Program.CreateMass(ref a, 50);
  136. Console.ReadLine();
  137. }
  138. else if (k == 2)
  139. {
  140. Program.PoUbivaniyu(ref a, 50);
  141. Console.ReadLine();
  142. }
  143. if (k == 3)
  144. {
  145. Program.PoVozrostaniy(ref a, 50);
  146. Console.ReadLine();
  147. }
  148.  
  149. Program.SortInsertMethod(ref a, 50);
  150. Program.ShakeSort(ref a, 50);
  151. Console.ReadLine();
  152. }
  153. }
  154. }

Решение задачи: «Как вычислить количество сравнений и перестановок?»

textual
Листинг программы
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4.  
  5. class Program
  6. {
  7.     static void Main()
  8.     {
  9.         var a = Enumerable.Range(1, 100).Reverse().ToArray();
  10.  
  11.         var comparer = new TrackingComparer<int>();
  12.         var swapper = new TrackingSwapper<int>();
  13.  
  14.         // Пузырик
  15.         for (int i = 0; i < a.Length; i++)
  16.         {
  17.             for (int j = i + 1; j < a.Length; j++)
  18.             {
  19.                 if (comparer.Compare(a[i], a[j]) > 0)
  20.                     swapper.Swap(ref a[i], ref a[j]);
  21.             }
  22.         }
  23.  
  24.         Console.WriteLine(string.Join(" ", a));
  25.         Console.WriteLine($"Comparisons: {comparer.ComparisonCount}");
  26.         Console.WriteLine($"Swaps: {swapper.SwapCount}");
  27.     }
  28. }
  29.  
  30. sealed class TrackingComparer<T> : IComparer<T>
  31. {
  32.     private readonly Func<T, T, int> _comparison;
  33.  
  34.     public TrackingComparer(Func<T, T, int> comparison)
  35.     {
  36.         _comparison = comparison ?? throw new ArgumentNullException(nameof(comparison));
  37.     }
  38.     public TrackingComparer(IComparer<T> comparer)
  39.     {
  40.         if (comparer == null)
  41.             throw new ArgumentNullException(nameof(comparer));
  42.  
  43.         _comparison = comparer.Compare;
  44.     }
  45.     public TrackingComparer() : this(Comparer<T>.Default)
  46.     {
  47.  
  48.     }
  49.  
  50.     public int ComparisonCount { get; private set; }
  51.  
  52.     public int Compare(T x, T y)
  53.     {
  54.         var result = _comparison(x, y);
  55.  
  56.         ComparisonCount++;
  57.         return result;
  58.     }
  59. }
  60. sealed class TrackingSwapper<T>
  61. {
  62.     public int SwapCount { get; private set; }
  63.  
  64.     public void Swap(ref T a, ref T b)
  65.     {
  66.         T c = a;
  67.         a = b;
  68.         b = c;
  69.  
  70.         SwapCount++;
  71.     }
  72. }

ИИ поможет Вам:


  • решить любую задачу по программированию
  • объяснить код
  • расставить комментарии в коде
  • и т.д
Попробуйте бесплатно

Оцени полезность:

11   голосов , оценка 3.909 из 5

Нужна аналогичная работа?

Оформи быстрый заказ и узнай стоимость

Бесплатно
Оформите заказ и авторы начнут откликаться уже через 10 минут
Похожие ответы