Suppose you are provided with the following function declaration in the C programming language.
int partition(int a[], int n);
The function treats the first element of a[]
as a pivot and rearranges the array so that all elements less than or equal to the pivot is in the left part of the array, and all elements greater than the pivot is in the right part. In addition, it moves the pivot so that the pivot is the last element of the left part. The return value is the number of elements in the left part.
The following partially given function in the C programming language is used to find the kth smallest element in an array a[]
of size n using the partition function. We assume k≤n
.
int kth_smallest (int a[], int n, int k)
{
int left_end = partition (a, n);
if (left_end+1==k) {
return a[left_end];
}
if (left_end+1 > k) {
return kth_smallest (___________);
} else {
return kth_smallest (___________);
}
}
The missing arguments lists are respectively
(a, left_end, k)
and(a+left_end+1, n-left_end-1, k-left_end-1)
(a, left_end, k)
and(a, n-left_end-1, k-left_end-1)
(a, left_end+1, n-left_end-1, k-left_end-1)
and(a, left_end, k)
(a, n-left_end-1, k-left_end-1)
and(a, left_end, k)
I found here a nice explanation about "How to find the kth largest element in an unsorted array of length n in O(n)?"
I've read partition , used in quick sort .Answer is given option (1).I agree with answer . But I need formal explanation .
Can you explain little bit please ?
Edit : AFAIK , Partition algorithm puts the chosen pivot in its correct position . We need recursively partition algorithm to find kth smallest element in an array .Partition algorithm run on a single side of array , either left or right of it's sorted pivot. I got stuck here . I'm thinking , it depends on kth index number ?