Search code examples
c#algorithmsortingmergesort

Editing a Merge Sort to sort in Descending Order C#


I am going through a sample piece of coursework that I had been sent by a friend to get myself ready for University coursework in my next year. I have been attempting to create a sorting and searching system to handle assorted data. For this task I have created a merge sort system which can sort my data in ascending order. However, I am unsure how I would edit this algorithm so it could sort in descending order instead. Could anyone possibly explain how this could be done?

The current algorithm handles string values.

Since this is based on a University task it requires myself to actually code the sorting and searching algorithms and not use the inbuilt functions available through Visual Studio.

static public void MainMerge<T>(T[] values, int left, int mid, int right) where T : IComparable<T>
    {
        int c = values.Length;
        T[] temp = new T[c];
        int i, eol, num, pos;

        eol = (mid - 1);
        pos = left;
        num = (right - left + 1);

        while ((left <= eol) && (mid <= right))
        {
            if (values[left].CompareTo(values[mid]) < 0)
                temp[pos++] = values[left++];
            else
                temp[pos++] = values[mid++];
        }

        while (left <= eol)
            temp[pos++] = values[left++];

        while (mid <= right)
            temp[pos++] = values[mid++];

        for (i = 0; i < num; i++)
        {
            values[right] = temp[right];
            right--;
        }
    }

    static public void SortMerge<T>(T[] values, int left, int right) where T : IComparable<T>
    {
        int mid;

        if (right > left)
        {
            mid = (right + left) / 2;
            SortMerge(values, left, mid);
            SortMerge(values, (mid + 1), right);

            MainMerge(values, left, (mid + 1), right);
        }
    }

Solution

  • You just need to change this: values[left].CompareTo(values[mid]) < 0 to this: values[left].CompareTo(values[mid]) >= 0. The merge phase is the only place where comparison is used.

    You can also pass a comparator to your sort function to allow a custom comparison predicate.

    There's one more way to do it: you can use your current algorithm and reverse the result.