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

Thuật toán sắp xếp nhanh (Quicksort-Demo Code)

10/16/2019 04:52:00 PM
  1. using System;
  2. namespace P04_QuickSort
  3. {
  4. class Program
  5. {
  6. static void Main(string[] args)
  7. {
  8. Console.Title = "Quick Sort";
  9. var numbers = new[] { -11, 12, -42, 0, 1, 90, 68, 6, -9 };
  10. Console.WriteLine("Original");
  11. Print(numbers);
  12. Sort(numbers);
  13. Console.WriteLine("Sorted:");
  14. Print(numbers);
  15. Console.ReadKey();
  16. }
  17. static void Swap<T>(T[] array, int i, int m)
  18. {
  19. T temp = array[i];
  20. array[i] = array[m];
  21. array[m] = temp;
  22. }
  23. static void Print<T>(T[] array)
  24. {
  25. Console.WriteLine(string.Join("\t", array));
  26. }
  27. static int Partition<T>(T[] array, int lower, int upper) where T : IComparable
  28. {
  29. var i = lower;
  30. var j = upper;
  31. T pivot = array[lower];
  32. do
  33. {
  34. while (array[i].CompareTo(pivot) < 0) i++;
  35. while (array[j].CompareTo(pivot) > 0) j--;
  36. if (i >= j) break;
  37. Swap(array, i, j);
  38. } while (i <= j);
  39. return j;
  40. }
  41. static void SubSort<T>(T[] array, int lower, int upper) where T : IComparable
  42. {
  43. if (lower < upper)
  44. {
  45. var p = Partition(array, lower, upper);
  46. SubSort(array, lower, p);
  47. SubSort(array, p + 1, upper);
  48. }
  49. }
  50. static void Sort<T>(T[] array) where T : IComparable
  51. {
  52. SubSort(array, 0, array.Length - 1);
  53. }
  54. }
  55. }

0 comments:

Post a Comment

 
Toggle Footer