简体   繁体   English

MergeSort 和 QuickSort 交换问题

[英]MergeSort and QuickSort swaps questions

In quickSort, given an array a[] = {1, 2, 3, 4, 5};在快速排序中,给定一个数组a[] = {1, 2, 3, 4, 5}; when I count swaps, it always returns 5 when it's sorted.当我计算交换时,它在排序时总是返回5 How is that?那个怎么样? I thought that swaps should be counted only when it actually swaps two numbers.我认为只有在实际交换两个数字时才应计算交换。 Another example - given an array a[] = {2, 1, 3, 4, 5};另一个例子 - 给定一个数组a[] = {2, 1, 3, 4, 5}; it returns swaps = 4 .它返回swaps = 4 I don't really understand how they work.我真的不明白他们是如何工作的。

int swapsQuick = 0;

int partition(int *L, int left, int right) {
    int pivot = left;
    int p_val = L[pivot];

    while (left < right) {
        while (L[left] <= p_val)
            left++;
        while (L[right] > p_val)
            right--;
        if (left < right) {
            swap(&L[left], &L[right]);
            swapsQuick++;
        }
    }
    swap(&L[pivot], &L[right]);
    swapsQuick++;
    return right;
}

int quicksort(int *L, int start, int end) {
    if (start >= end)
        return swapsQuick;
    int splitPoint = partition(L, start, end);
    quicksort(L, start, splitPoint - 1);
    quicksort(L, splitPoint + 1, end);
    return swapsQuick;
}

Also, which part of this mergeSort help function actually swaps two numbers?另外,这个mergeSort的哪一部分帮助 function 实际上交换了两个数字?

void merge(int arr[], int l, int m, int r) {
    int i, j, k;
    int n1 = m - l + 1;
    int n2 =  r - m;

    int L[n1], R[n2];

    for (i = 0; i < n1; i++)
        L[i] = arr[l + i];

    for (j = 0; j < n2; j++)
        R[j] = arr[m + 1+ j];

    i = 0;
    j = 0;
    k = l;
    while (i < n1 && j < n2) {
        if (L[i] <= R[j]) {
            arr[k] = L[i];
            i++;
        } else {
            arr[k] = R[j];
            j++;
        }
        k++;
    }
    while (i < n1) {
        arr[k] = L[i];
        i++;
        k++;
    }
    while (j < n2) {
        arr[k] = R[j];
        j++;
        k++;
    }
}

There is a problem in your partition function that may explain the incorrect count:您的partition function 存在问题,这可能解释了不正确的计数:

  • the loop while (L[left] <= p_val) left++;循环while (L[left] <= p_val) left++; may go beyond the end of the array if the pivot chosen is the smallest element of the slice, which is always the case for a sorted slice.如果选择的 pivot 是切片的最小元素,则 go 可能会超出数组的末尾,对于排序切片来说总是如此。 You should change it to:您应该将其更改为:

     while (left <= right && L[left] <= p_val) left++;

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

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