I'm studying quick-sort in the course of Algorithms 4th, Robert Sedgewick.
I want to know the following partition of quicksort code's the number of compare in an array of length N.
private static int partition(Comparable[] a, int lo, int hi)
{
int i = lo, j = hi+1;
while (true)
{
while (less(a[++i], a[lo]))
if (i == hi) break;
while (less(a[lo], a[--j]))
if (j == lo) break;
if (i>= j) break;
exch(a, i, j);
}
exch(a, lo, j);
return j;
}
I want to know T(n) of code described above. ( compare )
In my thought, it takes ~2N compares.
The reason is because it takes N compares for i
to move from left to right, and for j
to move right to left respectively in an already sorted array such as an array (A,B,C,D,E,F,G,H).
compare = less()
该分区函数的时间复杂度为T(n) = O(n)
My god, it's my mistake in the iteration of i
.
In the course of finding i
to stop, that takes only 1 compares.
So, It takes ~N Compares.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.