I'm learning C at the moment and chose implementing quicksort as an exercise.
My code is sorting correctly, but afterwards I looked at some tutorials online about quicksort. And they implement it differently.
I don't know, if I misunderstood quicksort, or if I simply implemented it differently.
How I understood quicksort:
- Choose pivot
- bin elements according to their size (bigger/smaller than pivot)
- repeat till array is sorted
I use middle element as pivot to avoid standard worst cases.
My code:
#include <stdio.h>
#include <math.h>
void quicksort(unsigned int* array, unsigned int length)
{
if (length <= 1)
{
return;
}
unsigned int length_tmp = length/2;
//pivot is middle element
unsigned int pivot = array[length_tmp];
unsigned int array_tmp[length];
unsigned int length_small = 0;
unsigned int length_big = 0;
//binning array - bigger / smaller
//left of pivot
for (unsigned int i = 0; i < length_tmp; i++)
{
if (array[i] < pivot)
{
array_tmp[length_small] = array[i];
length_small++;
}
else
{
array_tmp[length-1-length_big] = array[i];
length_big++;
}
}
//right of pivot
for (unsigned int i = length_tmp+1; i < length; i++)
{
if (array[i] < pivot)
{
array_tmp[length_small] = array[i];
length_small++;
}
else
{
array_tmp[length-1-length_big] = array[i];
length_big++;
}
}
//inserting pivot unsigned into temporary array
array_tmp[length_small] = pivot;
//copying values unsigned into array
for (unsigned int i = 0; i < length; i++)
{
array[i] = array_tmp[i];
}
//recursive function calls
quicksort(array+0, length_small);
quicksort(array+length_small+1, length_big);
return;
}
int main()
{
unsigned int array[] = {1,2,3,7,8,9,6,5,4,0};
unsigned int length = sizeof array / sizeof array[0]; //alternative: sizeof array / sizeof *array
//printing array
printf("unsorted array: ");
for (unsigned int i = 0; i < length; i++)
{
printf("%d", array[i]);
}
printf("\n");
//calling sorting function
quicksort(array, length);
//printing array
printf("sorted array: ");
for (unsigned int i = 0; i < length; i++)
{
printf("%d", array[i]);
}
printf("\n");
return 0;
}
I had posted this before on stackoverflow, but was informed of my mistake and that I should post it here. I didn't get answer to my question in that short time, but a few pointers regarding my code which I tried to implement in my solution.