繁体   English   中英

快速排序,以降序排列,而不是升序排列

[英]Quick Sort, sort in Descending order, instead of Ascending

我已经写了一个快速排序算法,它以升序对数组进行排序。 我正在尝试更改程序,以便按降序对数组进行排序。 听起来很简单,但我不确定要更改程序的哪些区域。 谢谢。

public static void Quick_Sort(ref double[] data, int left,int right, ref int count)
    {
        int i;      
        int j;      
        double pivot;      
        double temp;        
        i = left;      
        j = right;     
        pivot = data[(left + right) / 2];                 
            do         
            {
                while ((data[i] < pivot) && (i < right)) i++;       
                count++;
                while ((pivot < data[j]) && (j > left)) j--;        
                count++;
                ;
                if (i <= j)     
                {
                    temp = data[i];     
                    data[i] = data[j];    
                    data[j] = temp;     
                    i++;        
                    j--;       
                    count++;
                }
            } while (i <= j);       
            if (left < j) Quick_Sort(ref data, left, j, ref count, order);     
            if (i < right) Quick_Sort(ref data, i, right, ref count, order);
}    



 public static void QuickSort(ref double[] data, int size, int order)
    {

        int count = 0;      
        Quick_Sort(ref data, 0, data.Length - 1, ref count, order);    
        Console.WriteLine("\n    Quick Sort\n    Number of Elements: {0}\n    Executed {1} times\n\n    Worse-Case: O(n^2)\n    Best-Case: O(n log n)\n    Average-Case: O(n log n)",size,  count);     
    }

将do-while循环中的while循环更改为:

while ((data[i] > pivot) && (i < right)) i++;
count++;
while ((pivot > data[j]) && (j > left)) j--;
count++;

在第一个循环中,将data[i] < pivot更改为data[i] > pivot ,在第二个循环中,将pivot < data[j]更改为pivot > data[j]

此处演示

与枢轴比较时,您应该更改符号。

while ((data[i] > pivot) && (i < right)) 
{
    i++;       
}

count++;

while ((pivot < data[j]) && (j > left)) 
{
    j--;        
}

count++;

这样就够了吗? (排序后)

var dataReversed = data.Reverse().ToArray();

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM