Partition sort programming problem

I need an algorithm to select the k-th maximum or smallest value. Values ​​will be ints. My instructor told me to use a modified splitting algorithm to find the kth largest or smallest value. Any suggestions?

+3
source share
2 answers

The following is a quickselect algorithm description. I assume you want to find the kth smallest value.

  • Take the first element of your array. This will be your core. Watch your position.

  • Divide the array based on this rotation. Elements smaller than your bar go to your bar in the array; more after your rod. (This step will move your rod. Keep track of its position in your array.)

  • Now you know that your core is larger than the pivot_positionnumber of elements. So your core is the smallest element ( pivot_position + 1) th.

    • If k is equal pivot_position + 1, you have found your kth smallest value. Congratulations, return pivot_positionas the position of this value in the array.

    • If k is less pivot_position + 1, you want some value that is less than your core. Look at the parts of the array in front of your rod for the kth smallest value.

    • k , pivot_position + 1, , - , . * k - (pivot_position + 1) * th ( (pivot_position + 1)).

++, , , :

int select(int *array, int left, int right, int k);
int partition(int *array, int left, int right, int pivot_position);

select , k. , array[left] ; array[right] ; right - left + 1 . select k- .

partition , . 0 pivot_position , , . ( , randomized quickselect, pivot_position.) partition , .

+4

STL partial_sort, k .

, std::partial_sort, .

STL nth_element. , , .

+1

Source: https://habr.com/ru/post/1708788/


All Articles