简体   繁体   中英

Ascending Merge Sort to Descending Order

As you can see guys currently I am stuck on this merge sort problem and I do not know how to convert this ascending program into descending order in the same format, if someone can help me it would be really kind of you. I am new to this sorting process and I am learning slowly by time, currently I'm a student. Would really appreciate your help guys!

private static void mergeSort(int[] array, int low, int high) 
{
    if (high <= low) 
        return;
    int mid = (low + high) / 2;
    mergeSort(array, low, mid);
    mergeSort(array, mid + 1, high);
    merge(array, low, mid, high);
}

private static void merge(int[] array, int low, int mid, int high) 
{
    int leftArray[] = new int[mid - low + 1];
    int rightArray[] = new int[high - mid];
    for (int i = 0; i < leftArray.length; i++)
        leftArray[i] = array[low + i];
    for (int i = 0; i < rightArray.length; i++)
        rightArray[i] = array[mid + i + 1];
    int leftIndex = 0;
    int rightIndex = 0;
    for (int i = low; i < high + 1; i++)
    {
        if (leftIndex < leftArray.length && rightIndex < rightArray.length) 
        {
            if (leftArray[leftIndex] < rightArray[rightIndex]) 
            {
                array[i] = leftArray[leftIndex];
                leftIndex++;
            }
            else
            {
                array[i] = rightArray[rightIndex];
                rightIndex++;
            }
        }
        else if (leftIndex < leftArray.length) 
        {
            array[i] = leftArray[leftIndex];
            leftIndex++;
        } 
        else if (rightIndex < rightArray.length) 
        {
            array[i] = rightArray[rightIndex];
            rightIndex++;
        }
    }
}

您需要做的就是更改比较项目的行if (leftArray[leftIndex] < rightArray[rightIndex])

if (leftArray[leftIndex] >= rightArray[rightIndex])

Nothing much really changes. Instead of this comparison

if (leftArray[leftIndex] < rightArray[rightIndex])

you need to do this comparison

if (leftArray[leftIndex] > rightArray[rightIndex])

Rest of the code stays the same.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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