我正在使用快速排序对数组进行排序.但是我把数组弄得一团糟.我试图找出错误,但失败了


#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;
}

我的方法是找到比数组的第一个元素小的数字。对其进行分区,然后在已分区的数组上调用qs。例如:-1 5 7 8 9 3分区写入1。则用1之前和1之后的两个阵列对其进行qs。这将递归地继续,直到start等于或大于end,end是我数组的第一个和最后一个索引。End表示数组的最后一个元素。这是我的密码。提前谢谢。

问题出现在while循环条件下。当它遇到与分区元素相同的元素时,循环就关闭了。(重复编号(

同样,if条件不考虑重复元素,即if(i>x或j<x(。应该是i>x或j<x.

计数返回应该是返回计数,而不是计数+1。这解决了我的问题。

相关内容

最新更新