Breaking News
Loading...
Wednesday, October 16, 2019

Thuật toán sắp xếp chọn trong C# (Demo Code)

10/16/2019 04:45:00 PM

  1. using System;
  2. namespace P01_SelectionSort
  3. {
  4. class Program
  5. {
  6. static void Main(string[] args)
  7. {
  8. Console.Title = "Selection Sort";
  9. var numbers = new[] {10, 3, 1, 7, 9, 2, 0};
  10. Sort(numbers);
  11. Console.ReadKey();
  12. }
  13. static void Swap<T>(T[] array, int i, int m)
  14. {
  15. T temp = array[i];
  16. array[i] = array[m];
  17. array[m] = temp;
  18. }
  19. static void Print<T>(T[] array)
  20. {
  21. Console.WriteLine(string.Join("\t", array));
  22. }
  23. static void Sort<T>(T[] array) where T : IComparable
  24. {
  25. for (int i = 0; i < array.Length - 1; i++)
  26. {
  27. int m = i;
  28. T minValue = array[i];
  29. for (int j = i + 1; j < array.Length; j++)
  30. {
  31. if (array[j].CompareTo(minValue) < 0)
  32. {
  33. m = j;
  34. minValue = array[j];
  35. }
  36. }
  37. Swap(array, i, m);
  38. Console.ForegroundColor = ConsoleColor.Yellow;
  39. Console.WriteLine($"Step {i+1}: i = {i}, m = {m}, min = {minValue}");
  40. Console.ResetColor();
  41. Print(array);
  42. Console.WriteLine();
  43. }
  44. }
  45. }
  46. }

0 comments:

Post a Comment

 
Toggle Footer