I have reimplemented the quicksort algorithms that takes a list and sorts it in non-decreasing order:
void qsort(int* l, int len)
{
if(len <= 1) return;
int pivot=0;
for(int i = 0; i<len; i++)
{
if(l[i]<l[pivot])
{
swap(l+i, l+pivot);
pivot=i;
}
}
qsort(l, pivot);
qsort(l+x+1, len-x);
}
void swap(int* x, int* y)
{
*x +=*y;
*y = *x -*y;
*x-= *y;
}
Here is a simple implementation:
#include <stdio.h>
void qsort(int* l, int len);
void swap(int* x, int* y);
int main()
{
int x;
scanf("%i",&x);
int l[x];
for(int i=0; i<x; i++) scanf("%i",l+i);
qsort(l ,x);
for(int i=0; i<x; i++) printf("%i\n",l[i]);
}
void qsort(int* l, int len)
{
if(len <= 1) return;
int pivot=0;
for(int i = 0; i<len; i++)
{
if(l[i]<l[pivot])
{
swap(l+i, l+pivot);
pivot=i;
}
}
qsort(l, pivot);
qsort(l+pivot+1, len-pivot);
}
void swap(int* x, int* y)
{
*x +=*y;
*y = *x -*y;
*x-= *y;
}
I want to know if my implementation is correct or not. Assuming that it is correct, how can the algorithm do better?
The conquering step takes linear time \$\mathcal{O}(n^2)\$ because the for
loop takes linear time, adding and subtracting takes another linear time, and dividing takes time of \$\mathcal{O}(log(n))\$, so it is of time \$\mathcal{O}(n^2 log_2 n)\$.
How can I optimize the code in order to decrease it to take conquer \$\mathcal{O}(n)\$ instead of \$\mathcal{O}(n^2)\$?