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

Sắp xếp nổi bọt (Bubble sort-Demo Code)

10/16/2019 04:50:00 PM
  1. using System;
  2. namespace P03_BubbleSort
  3. {
  4. class Program
  5. {
  6. static void Main(string[] args)
  7. {
  8. Console.Title = "Bubble Sort";
  9. var numbers = new[] { 9, 1, 5, 2, 4, 6, 3 };
  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 (var i = 0; i < array.Length-1; i++)
  26. {
  27. for (var j = 0; j < array.Length - i - 1; j++)
  28. {
  29. if (array[j].CompareTo(array[j + 1]) > 0)
  30. {
  31. Swap(array, j, j + 1);
  32. }
  33. }
  34. Console.ForegroundColor = ConsoleColor.Yellow;
  35. Console.Write($"Step {i+1}:\t");
  36. Console.ResetColor();
  37. Print(array);
  38. Console.WriteLine();
  39. }
  40. }
  41. }
  42. }

0 comments:

Post a Comment

 
Toggle Footer