Advertisement
Guest User

Untitled

a guest
Mar 25th, 2019
67
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.31 KB | None | 0 0
  1. /// <summary>
  2. /// An in-place quicksort implementation based on the Hoare partition scheme.
  3. /// </summary>
  4. /// <typeparam name="T">The type of the elements being sorted.</typeparam>
  5. /// <param name="input">A span of elements to be sorted.</param>
  6. public static void Quicksort<T>(Span<T> input) where T : IComparable<T>
  7. {
  8. Quicksort<T>(input, Comparer<T>.Default);
  9. }
  10.  
  11. /// <summary>
  12. /// An in-place quicksort implementation based on the Hoare partition scheme.
  13. /// </summary>
  14. /// <typeparam name="T">The type of the elements being sorted.</typeparam>
  15. /// <param name="input">A span of elements to be sorted.</param>
  16. /// <param name="comparer">The comparer to use when comparing the elements.</param>
  17. public static void Quicksort<T>(Span<T> input, IComparer<T> comparer)
  18. {
  19. if (input.Length <= 1) { return; } // Base case
  20.  
  21. T pivot = input[(input.Length - 1) / 2];
  22.  
  23. int i = -1;
  24. int j = input.Length;
  25.  
  26. while (true)
  27. {
  28. while (comparer.Compare(input[++i], pivot) < 0) ;
  29. while (comparer.Compare(input[--j], pivot) > 0) ;
  30.  
  31. if (i >= j)
  32. {
  33. Quicksort(input.Slice(0, j + 1), comparer);
  34. if (j + 1 < input.Length) Quicksort(input.Slice(j + 1), comparer);
  35. return;
  36. }
  37.  
  38. T temp = input[i];
  39. input[i] = input[j];
  40. input[j] = temp;
  41. }
  42. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement