Hi, I'm getting segmentation fault errors when I use quicksort with ~350 000+ numbers.
This is the quick sort algorithm I'm using:
void swap(int* v, int i, int j)
{
int tmp = v[i];
v[i] = v[j];
v[j] = tmp;
}
int partition(int *v, int s, int e)
{
int p = v[e], i = s - 1;
for (int j = s; j < e; j++)
{
if (v[j] <= p)
{
i++;
swap(v, i, j);
}
}
i++;
swap(v, i, e);
return i;
}
void quicksort(int* v, int s, int e)
{
if (s < e)
{
int p = partition(v, s, e);
quicksort(v, s, p - 1);
quicksort(v, p + 1, e);
}
}
void quicksort(int* v, int n)
{
quicksort(v, 0, n-1);
}
and this is how I am testing it:
void generate_vector(int* &vec, int n)
{
vec = new int[n];
int i = 0;
while (vec[i++] = --n);
}
int main()
{
const int n = 350 * 1000;
int *vec = 0;
generate_vector(vec, n);
quicksort(vec, n);
int i = 0;
while (i < n) // check if is sorted
{
if (vec[i] != i)
{
std::cout << "error" << std::endl;
break;
}
i++;
}
delete[] vec;
return 0;
}
Why is this happening?
It works fine when I try less than 340 000, is the quicksort algorithm wrong or something else?
Sorry for the bad English.