Having trouble getting my quicksort function to work. Been trying to figure out what's wrong with it for several hours.
I'm trying to sort the following arrays:
int a[12] = { 13, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12 };
int b[12] = { 15, 48, 32, 46, 33, 19, 57, 16, 24, 30, 39, 47 };
int c[12] = { 27, 19, 26, 48, 16, 50, 56, 30, 13, 44, 53, 22 };
int d[12] = { 9, 39, 2, 22, 8, 53, 46, 59, 15, 38, 14, 44 };
int e[12] = { 29, 59, 35, 2, 13, 36, 31, 9, 3, 1, 20, 24 };
It sorts the array a[] just fine, but for some reason can't sort the rest.
Here's my code:
int quicksort(int data[], unsigned int n)
{
unsigned int pivot_index;
unsigned int n1;
unsigned int n2;
if (n > 1)
{
partitiony(data, n, pivot_index);
n1 = pivot_index;
n2 = n - n1 - 1;
quicksort(data, n1);
quicksort((data + pivot_index + 1), n2);
}
}
and the partitiony function:
int partitiony(int data[], unsigned int n, unsigned int& pivot_index)
{
int pivot = data[0];
int too_big_index = 1;
int too_small_index = n-1;
while(too_big_index <= too_small_index)
{
while ((too_big_index < n) && (data[too_big_index] <= pivot))
{
too_big_index++;
}
while(data[too_small_index] > pivot)
{
too_small_index--;
}
if(too_big_index < too_small_index)
{
swap(too_big_index, too_small_index);
}
pivot_index = too_small_index;
swap(data[pivot_index],data[0]);
data[pivot_index] = pivot;
}
}