简体   繁体   English

我的quicksort实施给出了错误的结果

[英]My quicksort implementation gives wrong result

today I've been working on Quicksort algorithm implementation in C. I thought that I've fully understood the issue, but after few attempts, the results weren't the same as I expected. 今天,我一直在使用C进行Quicksort算法的实现。我认为我已经完全理解了这个问题,但是经过几次尝试,结果却与我预期的不同。 I ask you for help in finding problem, because I can't find it on myself, I've even tried to look at another implementations in internet, and rewriting my functions, but nothing worked. 我请求您帮助发现问题,因为我自己找不到问题,我什至尝试查看Internet上的另一种实现并重写我的功能,但没有任何效果。 My code: 我的代码:

#include <stdio.h>
#include <stdlib.h>
#include <time.h>

void swap(int *x, int *y)
{
    int temp = *y;
    *x = *y;
    *y = temp;
}

void printArray(int arr[], int size)
{
    for(int i = 0; i < size; i++)
    {
        printf("%d ", arr[i]);
    }
    printf("\n");

}

int partition(int arr[], int low, int high)
{
    int pivot = arr[high];
    int i = (low - 1);
    for(int j = low; j <= high-1; j++)
    {
        if(arr[j] <= pivot)
        {
            i++;
            swap(&arr[i], &arr[j]);
        }
    }
    swap(&arr[i+1], &arr[high]);
    return(i+1);
}

void quickSort(int arr[], int low, int high)
{
    if(low < high)
    {
        int pi = partition(arr, low, high);
        quickSort(arr, low, pi-1);
        quickSort(arr, pi + 1, high);
    }
}


int main()
{
    srand(time(NULL));
    int arr[10];
    for(int i = 0;  i < 10; i++)
    {
        arr[i] = rand()%200 - 100;
    }

    printArray(arr, 10);
    quickSort(arr, 0, 9);
    printArray(arr, 10);
    return 0;
}

Examplatory results: 示范性结果:

-57 4 -30 -23 25 -67 83 26 -51 14 
-67 -67 -51 -67 -51 -51 14 -51 14 14

The only problem with your quick-sort is that the swap function is not implemented correctly. 快速排序的唯一问题是交换功能未正确实现。

The correct implementation should be something like: 正确的实现应类似于:

void swap(int *x, int *y) {
    int temp = *x;
    *x = *y;
    *y = temp;
}

You may be interested in looking at some other quick-sort variant, for that see this . 您可能会对其他快速排序变体感兴趣,为此请参见this

A humble suggestion: Use Randomized Quick sort : It would also be better if you don't always select the last element as your pivot (what you can do here is just before starting to sort select any random element and then swap it with the last element of your array. Using this strategy you don't have to make much changes in your existing code) This selection of random element as pivot is much better. 一个卑微的建议: 使用随机快速排序 :如果您不总是选择最后一个元素作为枢轴,这也更好(您可以在开始对任何随机元素进行排序之前将其替换为最后一个,这是可以做的)数组的元素。使用此策略,您不必在现有代码中进行太多更改)选择随机元素作为枢轴要好得多。 See this link for more details. 有关更多详细信息,请参见此链接。

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

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