I was brushing up on sorting algorithims so I went and wrote a quick sort.It runs successfully and its fast. I looked at some source code online and my code bore no resemlence whatsoever to it so I will post it and ask the following questions.
1:Is this a correct implementation of the quicksort?
1a:If not what is it and how does it differ?
1b:If it is then why is my code so different that all the implementations I see online. Rephrased: Whay poor design desicions did I make?
WR
1:Is this a correct implementation of the quicksort?
1a:If not what is it and how does it differ?
1b:If it is then why is my code so different that all the implementations I see online. Rephrased: Whay poor design desicions did I make?
Code:
void Qsort(int *list, int size,bool tomuchrecursion)
{
if (!tomuchrecursion)
_Qsort(list,0,size-1);
else
_QsortIt(list,size);
}
void _Qsort(int *list, int low, int high)
{
if (low>=high) return;
bool anchor = false;
int l=low;
int h=high;
int tempi;//variable for swapping
while (l<h)
{
if (list[l]>list[h]) //swap if out of order
{
tempi=list[l];
list[l]=list[h];
list[h]=tempi;
anchor =!anchor;
}
if (anchor)
l++;
else
h--;
}
_Qsort(list,low,h-1);//low side
_Qsort(list,l+1,high);//high side
}
void _QsortIt(int *list, int size)
{
std::stack< int> thestack;
thestack.push(0);
thestack.push(size-1);
int low,l,high,h,tempi;//declared outside loop because it (should be) tight
bool anchor;
while(!thestack.empty())
{
high=thestack.top();
thestack.pop();
low=thestack.top();
thestack.pop();
if (low<high)
{
anchor = false;
l=low;
h=high;
while (l!=h)
{
if (list[l]>list[h]) //swap if out of order
{
tempi=list[l];
list[l]=list[h];
list[h]=tempi;
anchor =!anchor;
}
if (anchor)
l++;
else
h--;
}
thestack.push(low);
thestack.push(h-1);
thestack.push(l+1);
thestack.push(high);
}
}
}
WR