I have to write and test quicksort for arrays which are sorted in 25%, 50%, 75%, 95%, 99% and 99.7% and when it is filled randomly. When I use array of size 500k my program go through random array and 25% sorted array without any problem(but 25% sorted array takes it 158s) but for 50% sorted array it throw segmentation fault and "Process returned 139(0x8b)." For smaller arrays, for example 100k, even sorted, everything works. How I generate my arrays( parameter "zakres" isn't needed, I know):
void generujTablice(int zakres,float sorted, int size_of_array)
{
Tablica = new int[size_of_array]; //allocating space for array
if(sorted == -1) //when array have to be sorted, but inverted
for(int i=0;i<size_of_array;i++)
Tablica[i] = size_of_array-i;
else
{
for(int i=0;i<sorted * size_of_array;i++) //example: if sorted is 0.25 array have to be sorted in 25% from beginning
Tablica[i] = i;
for(int i=sorted * size_of_array;i<size_of_array;i++) //rest of array is filled randomly but values have to be bigger than these in sorted part of array
Tablica[i] = rand()%int(size_of_array)+sorted * size_of_array;
}
}
And my quicksort: (Note: I am choosing the first element as a pivot, because I want to check the worst case of algorithm. I have commented line with randomly mixing first element with another one, and when I use this swap everything works fine and very very quickly. lewy == left, prawy == right)
#include <algorithm>
void quicksort(int * Tablica, int lewy, int prawy)
{
if(lewy<prawy)
{
//swap( Tablica[lewy], Tablica[rand()%(prawy-lewy)+lewy]);
int x = Tablica[lewy];
int i = lewy, j = prawy;
do{
while(Tablica[i] < x ) i++;
while(Tablica[j] > x ) j--;
if( i<=j ) swap( Tablica[i++], Tablica[j--] );
}while(i<=j);
quicksort(Tablica,lewy,j);
quicksort(Tablica,i,prawy);
}
}
I am using ubuntu. I tried to google what is wrong, but it seems to me that my algorithm is almost identical to some of these I found, so I have no idea how I can fix it. Sorry for my english, unfortunately, I am not using it very often.
Thanks for helping me.
quicksort
? - 500 - Internal Server Error}while(i<=j);
- I think this needs to be<
, not<=
. - 500 - Internal Server Error