简体   繁体   中英

MergeSort and QuickSort swaps questions

In quickSort, given an array a[] = {1, 2, 3, 4, 5}; when I count swaps, it always returns 5 when it's sorted. 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}; it returns 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?

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:

  • the loop 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. You should change it to:

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

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