示例#1
0
文件: Sorting.cs 项目: olesar/Altaxo
        /// <summary>
        /// Sorts elements in an order provided by the comparism method. Needs N log N operations. Worst case (already sorted) is something like 20% slower.
        /// </summary>
        /// <param name="count">Number of elements to sort (from indices 0 to count-1).</param>
        /// <param name="compare">A compare method wich takes two indices and compares the elements at those indices.</param>
        /// <param name="swap">A swap method which swaps the elements at two indices.</param>
        private static void HeapSort(int count, RowComparismMethod compare, RowSwapMethod swap)
        {
            int N;
            int k;

            if (count == 0)
            {
                return;           // No data to sort
            }

            /* We have n_data elements, last element is at 'n_data-1', first at
             *                         '0' Set N to the last element number. */

            N = count - 1;

            k = N / 2;
            k++;                    // Compensate the first use of 'k--'
            do
            {
                k--;
                downheap(N, k, compare, swap);
            }while (k > 0);

            while (N > 0)
            {
                // first swap the elements
                swap(0, N);

                // then process the heap
                N--;

                downheap(N, 0, compare, swap);
            }
        }
示例#2
0
文件: Sorting.cs 项目: olesar/Altaxo
        private static void downheap(int N, int k, RowComparismMethod CMP, RowSwapMethod swap)
        {
            while (k <= N / 2)
            {
                int j = 2 * k;

                if (j < N && CMP(j, j + 1) < 0)
                {
                    j++;
                }

                if (CMP(k, j) < 0)
                {
                    swap(j, k);
                }
                else
                {
                    break;
                }

                k = j;
            }
        }