/// <summary> /// Executes a quicksort algorithm given the value and swap methods. /// </summary> public static void Sort(Func <long, long> value, Action <long, long> swap, long left, long right) { if (left < right) { var stack = new System.Collections.Generic.Stack <Pair>(); stack.Push(new Pair(left, right)); while (stack.Count > 0) { var pair = stack.Pop(); var pivot = QuickSort.Partition(value, swap, pair.Left, pair.Right); if (pair.Left < pivot) { stack.Push(new Pair(pair.Left, pivot - 1)); } if (pivot < pair.Right) { stack.Push(new Pair(pivot + 1, pair.Right)); } } } }
public static void Sort(Func <long, long> value, Action <long, long> swap, long left, long right) { if (left >= right) { return; } Stack <QuickSort.Pair> pairStack = new Stack <QuickSort.Pair>(); pairStack.Push(new QuickSort.Pair(left, right)); while (pairStack.Count > 0) { QuickSort.Pair pair = pairStack.Pop(); long num = QuickSort.Partition(value, swap, pair.Left, pair.Right); if (pair.Left < num) { pairStack.Push(new QuickSort.Pair(pair.Left, num - 1L)); } if (num < pair.Right) { pairStack.Push(new QuickSort.Pair(num + 1L, pair.Right)); } } }
/// <summary> /// Partitions everything between left and right in three partitions, smaller than, equal to and larger than pivot. /// </summary> /// <remarks>Reference : https://en.wikipedia.org/wiki/Dutch_national_flag_problem </remarks> public static void ThreewayPartition(Func <long, long> value, Action <long, long> swap, long left, long right, out long highestLowest, out long lowestHighest) { QuickSort.ThreewayPartition(value, swap, left, right, left, out highestLowest, out lowestHighest); // default, the left a pivot. }