Exemple #1
0
        static void Main(string[] args)
        {
            var data = new SwappableData(5, 2, 7, 4, 1, 6, 3);
            PartitionStrategy partition = PartitionUtil.DoublePointerPartition;

            Quicksort(data, 0, data.Length - 1, partition);
            Console.WriteLine(data);
        }
Exemple #2
0
 static void Quicksort(SwappableData data, int begin, int end, PartitionStrategy partition)
 {
     if (begin < end)
     {
         var mid = partition(data, begin, end);
         Quicksort(data, begin, mid, partition);
         Quicksort(data, mid + 1, end, partition);
     }
 }
Exemple #3
0
        internal static int BasicPartition(SwappableData data, int begin, int end)
        {
            var pivot      = data[begin];
            var rightBegin = begin + 1;

            for (var i = rightBegin; i <= end; i++)
            {
                if (data[i] < pivot)
                {
                    data.Swap(i, rightBegin);
                    rightBegin++;
                }
            }

            var mid = rightBegin - 1;

            data.Swap(begin, mid);
            return(mid);
        }
Exemple #4
0
        internal static int DoublePointerPartition(SwappableData data, int begin, int end)
        {
            var mid   = (int)((begin + end) / 2);
            var pivot = MedianOfThree(data[begin], data[mid], data[end]);
            var i     = begin - 1;
            var j     = end + 1;

            while (true)
            {
                while (true)
                {
                    i++;
                    if (data[i] >= pivot)
                    {
                        break;
                    }
                }
                while (true)
                {
                    j--;
                    if (data[j] <= pivot)
                    {
                        break;
                    }
                }
                if (i < j)
                {
                    if (data[i] != data[j])
                    {
                        data.Swap(i, j);
                    }
                }
                else
                {
                    return(j);
                }
            }
        }