quicksort partition algorithm
Aug 31, 2013 at 10:59am UTC
I am trying to code a partition quicksort but the problem here is at the output is in an infinite loop:
the input : 4 3 5 7 2
the expected output : 2 3 4 5 7
but my output is infinite :
2 3 4 5 7
2 3 4 5 7
2 3 4 5 7
.
.
and so on
what is the solu ?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75
#include <vector>
#include <iostream>
#include <algorithm>
using namespace std;
/* Head ends here */
void partition(vector <int > ar) {
int temp,j=ar.size()-1,i=1,k=0,turn = 0,on_off=1;
do {
if (ar[j]<ar[k]&&turn==1&&on_off==1)
{
temp = ar[j];
for (int x = j;x>=k;x--)
{
if (x!=0&&j!=k)
{ar[x] = ar[x-1];}
}
k++;
j--;
ar[0] = temp;
turn = 0;
on_off = 0;
}
if (ar[j]>ar[k]&&turn==1&&on_off == 1)
{
j--;
turn = 0;
on_off = 0;
}
if (ar[i]<ar[k]&&turn==0&&on_off == 1)
{
temp = ar[i];
for (int x = i;x>=k;x--)
{
if (x!=0&&i!=k)
{ar[x] = ar[x-1];}
}
k++;
i++;
ar[0] = temp;
turn = 1;
on_off = 0;
}
if (ar[i]>ar[k]&&turn==0&&on_off == 1)
{
i++;
turn = 1;
on_off = 0;
}
on_off = 1;
for (int z = 0;z<ar.size();z++)
{
cout<<ar[z];
}
cout<<endl;
}while (j+1!=i);
}
/* Tail starts here */
int main(void ) {
vector <int > _ar;
int _ar_size;
cin >> _ar_size;
for (int _ar_i=0; _ar_i<_ar_size; _ar_i++) {
int _ar_tmp;
cin >> _ar_tmp;
_ar.push_back(_ar_tmp);
}
partition(_ar);
return 0;
}
Aug 31, 2013 at 3:39pm UTC
Topic archived. No new replies allowed.