Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Write the following function: void find_three_smallest(int a[], int n, int *smal

ID: 669983 • Letter: W

Question

Write the following function: void find_three_smallest(int a[], int n, int *smallest, in *second_smallest, int * third_smallest); When passed an array "a" of length "n", the function will search for its smallest, second smallest and third smallest element, storing them in the variable pointed to by smallest, second_smallest, and thirdsmallcst respectively. In case of a tie, it can put one to lie smallest and another one to be second smallest, E.g. = {1,5,4,5,1 ,2} the smallest, second_smallest, and third_smallest will be 1,1, and 2 respectively.

Explanation / Answer

Answer

void find_three_Smallest(int arr[], int arr_size,int *smallest,int *second_smallest,int *third_smallest )
{
    int i, first, second,third;

    /* There should be atleast two elements */
    if (arr_size < 2)
    {
        printf(" Invalid Input ");
        return;
    }

    first = second = INT_MAX;
    for (i = 0; i < arr_size ; i ++)
    {
        /* If current element is smaller than first then update both
          first and second */
        if (arr[i] < first)
        {
            second = first;
            smallest= arr[i];
        }

        /* If arr[i] is in between first and second then update second */
        else if (arr[i] < second && arr[i] != smallest)
            second_smallest = arr[i];
else if (arr[i] < third && arr[i] != smallest&& arr[i] != second_smallest)
            third_smallest = arr[i];
    }
    if (second == INT_MAX)
        printf("There is no second smallest element ");
    else
        printf("The smallest element is %d and second Smallest element is %d third Smallest element is %d ",
              smallest, second_smallest,third_smallest);
}