I am trying to create a quick sort function that sorts a vector based on the sting value it holds or the int value it holds. I have two different methods for quick sort that I'm using, but I only need one of them to work. As soon as one works, I'll copy it over to the other function.
Option A sorts the vector, but only in clumps which are not sorted (ex: vector {0,4,1,7,3,8,9,2,5,6} would turn into {0,1,2,3,7,8,9,4,5,6}, something like that)
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
|
void quickSortA(vector<int>& A, int p, int q)
{
int r;
if(p>=q) return;
int mid = p + (q - p)/2;
swap(A[mid],A[p]);
r=partitionA(A, p, q, x);
swap(A[p],A[r]);
quickSortA(A,p,r);
quickSortA(A,r+1,q);
}
int partitionA(vector<int>& A, int p, int q, int x)
{
for(int i = x; i < right; i++)
{
if (A[i] <= x)
{
swap(A[i], A[left]);
left++;
}
}
return left - 1;
}
|
Option B hits a segmentation fault at the marked line
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
|
void quickSortB(vector<int>& A, int p,int q)
{
int r;
if(p<q)
{
r=partitionB(A, p,q);
//Seg fault happens here after program loops multiple times, doesn't seem to even try to go to partitionB
quickSortB(A,p,r);
quickSortB(A,r+1,q);
}
}
int partitionB(vector<int>& A, int p,int q)
{
int x= A[p];
int i=p;
int j;
for(j=p+1; j<q; j++)
{
if(A[j]<=x)
{
i=i+1;
swap(A[i],A[j]);
}
}
swap(A[i],A[p]);
return i;
}
|
in both cases, the initial values of p and q are 0 and size-1, respectively.