Okay I have an assignment to find the Kth smallest element in the list using several different methods….
first method is to sort the list, then return the Kth smallest element. easy, my mentality is say the list = 10 elements, sort the list in ascending order, then return the element in the 10th position
next method uses the Partition from Quicksort:
“The second algorithm is to apply the procedure Partition used in Quicksort. The procedure partitions an array so that all elements smaller than some pivot item come before it in the array and all elements larger than that pivot item come after it. The slot at which the pivot item is located is called the pivotposition. We can solve the Selection Problem by partitioning until the pivot item is at the kth slot. We do this by recursively partitioning the left subarray if k is less than pivotposition, and by recursively partitioning the right subarray if k is greater than pivotposition. When k = pivotposition, we’re done.”
Say I have a list of 10 items:
3 8 9 2 4 5 1 7 10 6, with 5 being the pivot.. I know I would normally would have 2 arrays
3 2 4 1 and 8 9 7 10 6
but what I don’t understand is: “We can solve the Selection Problem by partitioning until the pivot item is at the kth slot.”
what is the kth slot? to me i keep thinking kth = the length of the array, so in this case 10. which would have the 6 value in it, which is obviously not the lowest… and isn’t correct.
can someone use this sample array and kinda just show me what this algorithm means and how it finds the kth/smallest element? thanks
I think you have looking at the solution in a complicated way.
This is how you find the kth smallest element using QuickSort (well not entirely quicksort, I will tell why).
In quicksort you choose a random pivot element and divide the entire array into two and recursively sort the left and the right subarrays to form the entire sorted array.
In this problem you don’t have to do that. All you are doing is,
So to address your doubt,