我正在使用快速排序对数组进行排序。但是我得到的是未排序的数组。我试图找出错误,但失败了
#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将它的wrt划分为1。然后qs它在1之前和1之后的两个数组。这将继续递归,直到start等于或大于end,这是我的数组的第一个也是最后一个索引。End表示数组的最后一个元素。这是我的代码。提前谢谢。
转载请注明出处:http://www.cjhyc.com/article/20230524/2264404.html