简体   繁体   English

我正在使用快速排序对数组进行排序。 但是我让数组未排序。 我试图找到错误但失败了

[英]I am using quick sort to sort an array. But am getting the array unsorted. I have tried to find the error but have failed

#include<iostream>
#include<algorithm>
#include<string.h>

using namespace std;

int partition(int input[], int start, int end)
{
    int x = input[start],count=0;

    for (int i=start+1;i<=end;i++)
    {
        if (input[i] <= x)
            count++;
    }

    int temp = input[start+count];
    input[start+count] = x;
    input[start] = temp;

    int i=start, j=end;

    while (input[i] != x && input[j] != x)
    {
        if (input[i] > x && input[j] < x)
        {
            int temp1 = input[j];
            input[j] = input[i];
            input[i] = temp1;

            i++;
            j--;
        }
        else if (input[i] <= x)
        {
            i++;
        }
        else
        {
            j--;
        }
    }

    return count+1;
}

void helpSort(int input[], int start, int end)
{
    if (start >= end)
        return;

    int c = partition(input, start, end);

    helpSort(input, start, start+c-1);
    helpSort(input, start+c+1, end);

    return;
}

void quickSort(int input[], int size)
{
    int start=0,end=size-1;

    helpSort(input, start, end);
}

int main()
{
    int arr[] = {1,3,7,2,6,4,8,9,0,5};

    quickSort(arr, 10);

    for (int i=0;i<10;i++)
    {
        cout<<arr[i]<<" ";
    }

    return 0;
}

My approach was to find numbers smaller than the first element of the array.我的方法是找到小于数组第一个元素的数字。 Partition it and then call qs on the partitioned array.对其进行分区,然后在分区数组上调用 qs 。 For eg:- 1 5 7 8 9 3 partitions it wrt to 1. then qs it with two arrays before 1 and after 1. This continues recursively till start is either equal to or greater than end which is the first and last index of my array.例如:- 1 5 7 8 9 3 将其分区为 1。然后在 1 之前和 1 之后用两个 arrays 对它进行 qs。递归继续直到 start 等于或大于 end ,这是我的第一个和最后一个索引大批。 End denotes the last element of my array. End 表示我的数组的最后一个元素。 This is my code.这是我的代码。 Thanks in advance.提前致谢。

The issue was in the while loop condition.问题出在 while 循环条件中。 When it encountered the same element as the one which was the partitioning element the loop closed.当它遇到与分区元素相同的元素时,循环关闭。 (duplicate numbers) (重复数字)

Also the if conditions did not consider duplicate elements ie if (i>x or j<x).此外,if 条件不考虑重复元素,即 if (i>x 或 j<x)。 It should have been i>x or j<=x.它应该是 i>x 或 j<=x。

The count return should have been returning count and not count+1.计数返回应该是返回计数而不是计数+1。 This solved the problem I had.这解决了我遇到的问题。

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

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