I tried to implement the Quicksort algorithm. Here is the code for the Quicksort itself
void quicksortlast(double* a, int first, int last)
{
if(first<last)
{
int pIndex=partition(a, first, last);
quicksortlast(a, first, pIndex-1);
quicksortlast(a, pIndex+1, last);
}
}
The pIndex variable is the location of the element which is at the right position. I choose the last array element as pivot in the partitioning scheme. The following code is supposed to partition the array:
int partition(double* a, int first, int last)
{
int pivot=last;
int i=0;
int j=last-1;
while(i<j && i<=last && j>=0)
{
while(a[i++]<a[pivot])
{
if(i>last)
break;
}
while(a[j--]>a[pivot])
{
if(j<0)
break;
}
if(i<j && i<=last && j>=0)
{
swap(a,i,j);
i++;
j--;
}
}
swap(a,j,pivot);
return j;
}
The partition function uses the swap function defined as
void swap(double* a, int left, int right)
{
int temp=a[left];
a[left]=a[right];
a[right]=temp;
return;
}
And, of course, there is the test.cpp function that tests the algo.
#include <iostream>
#include "qsort.h"
using namespace std;
int main()
{
int len;
cin>>len;
double* a= new double[len];
for(int i=0;i<len;i++)
cin>>a[i];
cout<<"Unsorted array"<<endl;
print(a,len);
quicksortlast(a, 0, len-1);
cout<<"printed array"<<endl;
print(a, len);
return 0;
}
The print function on its first call prints the unsorted array but the it gives me error an message :
Segmentation fault(core is dumped).
I understand, that some memory location is accessed, but I do not understand where the actual mistake lies. Any help is highly appreciated.