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

Write a C Program: Using qsort, write a void function named sort with 2 args: an

ID: 3844589 • Letter: W

Question

Write a C Program: Using qsort, write a void function named sort with 2 args:

an array of ints, which I'll call a.

an unsigned that is the number of elements in the array.

sort may assume without checking that a has at least one element, and that all the

values in a are in the range [10, 999].

sort's job is to sort the array a so that

All the 2-digit numbers come before all the 3-digit numbers.

All the 2-digit numbers are in decreasing order.

All the 3-digit numbers are in decreasing order.

For example if the array held {100, 22, 200, 11} on entry, your sort function wouldchange it to {22, 11, 200, 100}

Explanation / Answer

Hi

I have written complete program with sort function as well as will main to test the function. Also I have heavily commented the code for deeper understanding.

//Code starts here

#include <stdio.h>
#include <stdlib.h>

int values[] = { 100, 22, 200, 11 };

//this is the compare function used by qsort()
int cmpfunc (const void * a, const void * b)
{

//return values are such that if a is greater than b by our logic, then
//a positive value is returned. If b is greater than our logic, then
//a negative value is returned. else 0 is returned (if a equals b)
  
int x = *(int*)a; //make a an integer
int y = *(int*)b; //make b an integer
  
int xDigits = (x < 100) ? 2 : 3; //find no of digits in x
int yDigits = (y < 100) ? 2 : 3; //find no of digits in y

//These if else statements are self explainatory
if(xDigits == 2 && yDigits == 3){
return -1;
}
if(xDigits == 3 && yDigits == 2){
return 1;
}
  
// if there are same no of digits then check which is bigger
// if x is bigger than y then return a -ve value since we want to sort
// from bigger number to smaller number
if(x > y){
return -1;
}else{
return 1;
}

//return 0 if both are equal
return 0;
}

//sort function taking an array and noOfElements if array
void sort(int a[], int noOfElements){
//qsort call
qsort(a, noOfElements, sizeof(int), cmpfunc);
}

int main()
{
//main function return for test purpose
int n;

printf("Before sorting, the list is: ");
for( n = 0 ; n < 4; n++ )
{
printf("%d ", values[n]);
}

sort(values, 4);

printf(" After sorting, the list is: ");
for( n = 0 ; n < 4; n++ )
{   
printf("%d ", values[n]);
}

printf(" ");
  
return 0;
}

//Code ends here

Hope it helps

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote