qsort geeksforgeeks code example

Example 1: qsort in c

#include <stdlib.h>
int cmpfunc (const void * a, const void * b) {
   return ( *(int*)a - *(int*)b );
}

int main () {
//n is number of elements in arr(size f that arr)
   qsort(arr, n, sizeof(int), cmpfunc);
   }

Example 2: analysis of quick sort

T(n) = 2*T(n/2) + n                        // T(n/2) = 2*T(n/4) + (n/2)    

        = 2*[ 2*T(n/4) + n/2 ] + n
	= 22*T(n/4) + n + n
	= 22*T(n/4) + 2n                       // T(n/4) = 2*T(n/8) + (n/4)

	= 22*[ 2*T(n/8) + (n/4) ] + 2n
	= 23*T(n/8) + 22*(n/4) + 2n
	= 23*T(n/8) + n + 2n
	= 23*T(n/8) + 3n

	= 24*T(n/16) + 4n
	and so on....

	= 2k*T(n/(2k)) + k*n      // Keep going until: n/(2k) = 1  <==> n = 2k    

	= 2k*T(1) + k*n
	= 2k*1 + k*n
	= 2k + k*n               // n = 2k
	= n + k*n
	= n + (lg(n))*n
        = n*( lg(n) + 1 )
       ~= n*lg(n))

Tags:

C Example