简体   繁体   English

QuickSort(分区Hoare)的修改,先偶数降序,再奇数降序

[英]Modification of QuickSort (partition Hoare), first even numbers descending, then odd numbers descending

I have a big problem to modify the Hoare partition so that it sorts in descending order: first by even numbers and then by odd numbers.我有一个大问题要修改 Hoare 分区,以便它按降序排序:首先按偶数,然后按奇数。 Example: arr[] = {1, 6, 7, 8, 4, 5}, out: arr[] = {8, 6, 4, 7, 5, 1}.示例:arr[] = {1, 6, 7, 8, 4, 5},输出:arr[] = {8, 6, 4, 7, 5, 1}。

I was able to do this by dividing the array separately into even and odd numbers and sorting each of these parts separately.我可以通过将数组分别分成偶数和奇数并分别对这些部分进行排序来做到这一点。 However, the task is to rework the quicksort so that you do not have to divide the array.但是,任务是重新处理快速排序,以便您不必划分数组。

Below I have my partition, I'm going in the right direction?下面我有我的分区,我正朝着正确的方向前进?

static int partition(int []arr, int low,  
                                int high) 
{ 
    int pivot = arr[low]; 
    int i = low - 1, j = high + 1; 

    while (true) 
    { 

        do
        { 
            i++; 
        } while ((arr[i] > pivot && ((arr[i]%2==0 && pivot%2==0) || (arr[i]%2!=0 && pivot%2!=0))) || (arr[i]<pivot && arr[i]%2==0 && pivot%2!=0)); 


        do
        { 
            j--; 
        } while (arr[j] < pivot); 

        if (i >= j) 
            return j; 
        int temp = arr[i]; 
        arr[i] = arr[j]; 
        arr[j] = temp; 
    } 
} 

You did an effort in the condition of the first loop, but:您在第一个循环的条件下做了一些努力,但是:

  • It is not entirely correct这并不完全正确
  • It should be applied similarly to the second loop condition as well它也应该类似地应用于第二个循环条件

For the second reason it may be good to define a compare-function:由于第二个原因,最好定义一个比较函数:

    private static int cmp(int a, int b) {
        if (a % 2 != b % 2) return a % 2 - b % 2; 
        return b - a;
    }

Now the loop conditions should be simple:现在循环条件应该很简单:

  • while (cmp(arr[i], pivot) < 0)
  • while (cmp(arr[j], pivot) > 0)

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

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