Example 1: quick sort program in c
#include<stdio.h>
void quicksort(int number[25],int first,int last){
int i, j, pivot, temp;
if(first<last){
pivot=first;
i=first;
j=last;
while(i<j){
while(number[i]<=number[pivot]&&i<last)
i++;
while(number[j]>number[pivot])
j--;
if(i<j){
temp=number[i];
number[i]=number[j];
number[j]=temp;
}
}
temp=number[pivot];
number[pivot]=number[j];
number[j]=temp;
quicksort(number,first,j-1);
quicksort(number,j+1,last);
}
}
int main(){
int i, count, number[25];
printf("How many elements are u going to enter?: ");
scanf("%d",&count);
printf("Enter %d elements: ", count);
for(i=0;i<count;i++)
scanf("%d",&number[i]);
quicksort(number,0,count-1);
printf("Order of Sorted elements: ");
for(i=0;i<count;i++)
printf(" %d",number[i]);
return 0;
}
Example 2: quicksort
// @see https://www.youtube.com/watch?v=es2T6KY45cA&vl=en
// @see https://www.youtube.com/watch?v=aXXWXz5rF64
// @see https://www.cs.usfca.edu/~galles/visualization/ComparisonSort.html
function partition(list, start, end) {
const pivot = list[end];
let i = start;
for (let j = start; j < end; j += 1) {
if (list[j] <= pivot) {
[list[j], list[i]] = [list[i], list[j]];
i++;
}
}
[list[i], list[end]] = [list[end], list[i]];
return i;
}
function quicksort(list, start = 0, end = undefined) {
if (end === undefined) {
end = list.length - 1;
}
if (start < end) {
const p = partition(list, start, end);
quicksort(list, start, p - 1);
quicksort(list, p + 1, end);
}
return list;
}
quicksort([5, 4, 2, 6, 10, 8, 7, 1, 0]);
Example 3: 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))