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

Thuật toán sắp xếp chèn (Insertion sort-Demo Code)

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

0 comments:

Post a Comment

 
Toggle Footer