Implement the following function $$\texttt{find_k}$$ :
$$\texttt{int find_k(int A[], int N, int k);}$$
where $$\texttt{A}$$ is an array of distinct positive numbers, $$\texttt{N}$$ the dimension of the array, and $$\texttt{k} > 0$$. The function calculates the k$$^{th}$$ smallest element in the array and returns this element or -1 if it doesn't exist.
Use $$\texttt{QuickSort}$$ in searching for this element without sorting the entire array.
Example : In the following array [11, 4, 7, 8, 2, 9, 23, 30, 10, 14]
The first smallest element is 2, the 2nd smallest element is 4, the 3rd smallest element is 7, $$\cdots$$
Difficulty level
Video recording
This exercise is mostly suitable for students
int place(int tab[], int i, int j)
{
int k,l, Aux;
l=i+1;
k=j;
while (l<=k)
{
while (tab[k]>tab[i] && k>=l )
k--;
/*now, tab[k]<=tab[i]*/
while (tab[l]<=tab[i] && l<=k)
l++;
/*now, tab[l]>tab[i]*/
if (l<k)
{
Aux = tab[l];
tab[l] = tab[k];
tab[k] = Aux;
l++;
k--;
}
}
/* place pivot tab[i] at k */
Aux = tab[i];
tab[i] = tab[k];
tab[k] = Aux;
return k;
}
int find_k(int tab[],int N,int k)
{
int start=0, end=N-1, j;
if (k>N || k<1)
return -1;
do
{
j=place(tab,start,end);
if (j>k-1)
end=j-1;
else
if (j<k-1)
start=j+1;
else
return(tab[j]);
}
while (1);
}
Back to the list of exercises
Looking for a more challenging exercise, try this one !!
Sorting using heap-sort algorithm