Question: Design and implement an algorithm that, when given a collection of int
ID: 3880081 • Letter: Q
Question
Question:
Design and implement an algorithm that, when given a collection of integers in an unsorted array, determines the third smallest number (or third minimum). For example, if the array consists of the values 21, 3, 25, 1, 12, and 6 the algorithm should report the value 6, because it is the third smallest number in the array. Do not sort the array.
To implement your algorithm, write a function thirdSmallest that receives an array as a parameter and returns the third-smallest number. To test your function, write a program that populates an array with random numbers and then calls your function.
Explanation / Answer
Hi friend, You have not mentuoned the Language, So i have implemented my function in C.
Please find my function:
void thirdSmallest(int arr[], int arr_size)
{
/* There should be atleast three elements */
if (arr_size < 3)
{
printf(" Invalid Input ");
return;
}
// Initialize first, second and third smallest element
int first = arr[0], second = INT_MAX, third = INT_MAX;
// Traverse array elements to find the third Largest
for (int i = 1; i < arr_size ; i ++)
{
/* If current element is smallest than first,
then update first, second and third */
if (arr[i] < first)
{
third = second;
second = first;
first = arr[i];
}
/* If arr[i] is in between first and second */
else if (arr[i] < second)
{
third = second;
second = arr[i];
}
/* If arr[i] is in between second and third */
else if (arr[i] < third)
third = arr[i];
}
printf("The third smallest element is %d ", third);
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.