Question: please fill the dots in the third picture with appropriate code. ... 7. To find the kth smallest element in an array, you can sort



... 7. To find the kth smallest element in an array, you can sort the array, but that takes at least O(n log(n)) time. You can do better than that. Use the partition function to rearrange the array elements so that all clements in the first portion are less than all the elements in the second portion Suppose there are j elements in the first portion. If ks), then the k-th smallest element must be the koth smallest element in the first portion. Recursively look there. Otherwise, the k-th smallest element must be in the second portion. It's not the kth elementyou need to adjust by the size of the discarded first portion. For example, suppose the array is partitioned like this: 4 8 67 92 11 15 19 13 To find the Sth smallest value, you look in the first portion. To find the 8th smallest value you look for the 2nd smallest value in the second portion. X = y: 12 lest value in the second portion. select.cpp 1/** 2 Swaps two integers. 3 @param x the first integer to swap 4 @param y the second integer to swap 5* 6 void swap(int& x, int& y) 7 8 int temp = x; 9 10 y = temp: 11 ) 13 / 14 Partitions a portion of an array. 15 @param a the array to partition 16 @param from the first index of the portion to be partitioned 17 @param to the last index of the portion to be partitioned 18 @return the last index j of the first partition so that all 19 values in a[from)...aljl are all values in ali+1]...ato). 20 */ 21 int partition(int all, int from, int to) 22 ( 23 int pivot = a[from): 24 int i = from - 1; 25 int j = to + 1; 26 while (i
Step by Step Solution
There are 3 Steps involved in it
Get step-by-step solutions from verified subject matter experts
