Write a function void sort(int* numbers, int n) to sort a given array of n integ
ID: 3687777 • Letter: W
Question
Write a function void sort(int* numbers, int n) to sort a given array of n integers in ascending order.
In the main function, declare an integer n and assign it a value of 20. Allocate memory for an array of n integers using malloc. Fill this array with random numbers, using the c math library random number generator rand(). Print the contents of the array.
Pass this array along with n to the sort(...) function above. Print the contents of the sorted array following the call to sort(...). You may *not* use the C provided sort function (e.g. qsort()).
Skeleton:
#include <stdio.h>
#include<stdlib.h>
#include<math.h>
void sort(int* number, int n){
/*Sort the given array number , of length n*/
}
int main(){
/*Declare an integer n and assign it a value of 20.*/
/*Allocate memory for an array of n integers using malloc.*/
/*Fill this array with random numbers, using rand().*/
/*Print the contents of the array.*/
/*Pass this array along with n to the sort() function of part a.*/
/*Print the contents of the array.*/
return 0;
}
Explanation / Answer
#include <stdio.h>
#include <stdlib.h>
void sort(int * no,int n)
{
int temp;
for(int i=0;i<n;i++)
{
for(int j=0;j<n;j++)
{
if(*(no+i)<*(no+j))
{
temp=*(no+i);
*(no+i)=*(no+j);
*(no+j)=temp;
}
}
}
}
int main()
{
int n=20,*no;
for(int i=0;i<n;i++)
{
no=(int*)malloc(n*sizeof(int));
}
srand(time(NULL));
printf("Elements in array are: ");
for(int i=0;i<n;++i)
{
*(no+i)=rand()%20;
printf("%d ",*(no+i));
}
sort(no,n);
printf(" Elements in array after sorting are: ");
for(int i=0;i<n;++i)
{
printf("%d ",*(no+i));
}
printf(" ");
return 0;
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.