【发布时间】:2013-08-09 06:17:39
【问题描述】:
我试图实现快速排序。但是控件似乎永远不会退出快速排序功能。任何帮助将不胜感激。
几点建议:
- 我使用第一个元素作为枢轴。我知道存在更好、更有效的技术来选择支点,但这与此无关。
2.分区函数中的'k'变量是pivot元素。
据我所知,问题出在分区函数上,因为我已经尝试过多次调试。
另外,这不是家庭作业问题。我是在自学后尝试实现的算法。
#include<iostream>
using namespace std;
void swap(int *a,int *b)
{
int temp;
temp=*a;
*a=*b;
*b=temp;
}
void readarray( int a[],int n)
{
cout<<"Enter elements for the array\n";
for(int i=0;i<n;i++)
cin>>a[i];
}
void printarray(int a[],int n)
{
cout<<"Elements are as follows\n";
for(int i=0;i<n;i++)
cout<<a[i]<<" ";
cout<<endl;
}
int partition(int low,int high,int a[])
{
int i,j,k;
i=low;
j=high;
k=low;
while(i<=j)
{
while(a[i]<a[k])
i++;
while(a[j]>=a[k])
j--;
if(i<=j)
{
swap(a[i],a[j]);
i++;
j--;
}
}
if(i>j)
swap(a[k],a[j]);
return j;
}
void quicksort(int low,int high,int a[])
{
int k;
if(low<high)
{
k=partition(low,high,a);
quicksort(low,k-1,a);
quicksort(k+1,high,a);
}
}
int main()
{
int a[20];
int n;
cout<<"Enter the size of the array\n";
cin>>n;
readarray(a,n);
cout<<"Before sorting\n";
printarray(a,n);
quicksort(0,n,a);
cout<<"After sorting contents are\n";
printarray(a,n);
return 0;
}
在主函数中,我尝试同时使用 quicksort(0,n,a) 和 quicksort(0,n-1,a)。都没有用。
【问题讨论】:
-
在交换函数中更喜欢使用引用而不是指针
-
这不应该编译,因为您将
int值(如a[i])传递给交换函数,而不是预期的指针值(如a+i)。 -
@Lee 使用引用的其他原因:)
-
您确定
while(a[i]<a[k]) i++;最终会停止吗?我认为它可以很容易地超出 a[]。 -
@LeeDanielCrocker 同意。此外,我不会在我的函数中使用
low、high和ar[],而是在调用方进行正确的数学运算并使用ar[]和len进入每个分区。代码感觉更干净(恕我直言)。
标签: c++ algorithm quicksort divide-and-conquer