quick sort time complexir=ty if sorted code example
Example 1: quicksort
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 2: analysis of quick sort
T(n) = 2*T(n/2) + n
= 2*[ 2*T(n/4) + n/2 ] + n
= 22*T(n/4) + n + n
= 22*T(n/4) + 2n
= 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
= 2k*T(1) + k*n
= 2k*1 + k*n
= 2k + k*n
= n + k*n
= n + (lg(n))*n
= n*( lg(n) + 1 )
~= n*lg(n))