Craig
Craig

Reputation: 35

Quick Sort, sort in Descending order, instead of Ascending

i have written a Quick Sort Algorithm and it sorts the array in ascending order. I am trying to alter the program so it sorts the array in descending order. Sounds simple enough, but i'm not sure which areas of the program to alter. Thanks.

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);     
    }

Upvotes: 0

Views: 3235

Answers (3)

Andrii Gudyma
Andrii Gudyma

Reputation: 1

You should alter signs while comparing to pivot.

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

count++;

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

count++;

Upvotes: 0

Slaven Tojić
Slaven Tojić

Reputation: 3014

Change the while loops in your do-while loop to:

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

In the first loop change data[i] < pivot to data[i] > pivot and in the second loop change pivot < data[j] to pivot > data[j].

DEMO HERE

Upvotes: 1

Vladi Pavelka
Vladi Pavelka

Reputation: 926

Wouldn't this suffice you? (after sorting)

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

Upvotes: 0

Related Questions