[Speaking algorithm small class] Find the k-th element of a sequence

K-th small element

[Algorithm process]

The process of dividing operations with the help of quick sort. Because each quick sort will place the pivot (the first element of the array is taken by default) in a certain position in the array, and the left and right elements are smaller or larger than the pivot itself (assuming ascending sorting). Therefore, the following process is obtained:
[1] After completing a quick sort, determine the new position of the pivot in the array. Because the index of the array starts at 0, if the index of the pivot i = k – 1, then the pivot is the k-th smallest element.
[2] If the subscript of the pivot axis i <k – 1, then the k-th smallest element is on the right side of the pivot axis, and the right side is recursively searched.
[3] If the subscript of the pivot i> k-1, then the k-th smallest element is on the left side of the pivot, and the left side is recursively searched.

【time complexity】

Best case:
T(n)=T(1/2 n)+O(n)
Each recursive call divides the original sequence into two sub-sequences of equal length. At this time, the time complexity is O(n).
Worst case: same as fast sorting, each recursive call divides the original sequence into pivots and two sub-sequences with length 0 and n-1. At this time, the time complexity is O(n^2).
The average time complexity is also O(n).
Insert picture description here

Guess you like

Origin blog.csdn.net/COFACTOR/article/details/108691457