Write a program that declares three arrays with N elements with random values be
ID: 3734615 • Letter: W
Question
Write a program that declares three arrays with N elements with random values between -100 to 100. Use “#define N 10” to set N to an arbitrary number before the main function. The define statement, the function prototypes, and the sample main function are provided below. I) Write a print_array2 function that prints the entires in an array of type double. II) Write a bubble sort function that sorts the elements in ascending or descending order depending on the value of the input argument order (0=ascending and 1=descending). III) Write an insertion sort function that sorts that numbers in an array in ascending order. VI) Compare the runtime of the bubble sort and the insertion sort functions (no submission required). //define N #define N 10 //function prototypes void print_array2(double array[], int length); void bubble_sort(double array[], int length, in order); void insertion_sort(double array[], int length); //sample main void main(){ double array1[N]; double array2[N]; double array3[N]; for(int i = 0; i < N;i++){ array1[i] = rand() % 200 - 100; array2[i] = rand() % 200 - 100; array3[i] = rand() % 200 - 100; } print_array2(array1,N); print_array2(array2,N); print_array2(array3,N); bubble_sort(array1,N,0); bubble_sort(array2,N,1); insertion_sort(array3,N); print_array2(array1,N); print_array2(array2,N); print_array2(array3,N); } in c programming
Explanation / Answer
#include <stdio.h>
#define N 10
/* function declaration*/
void print_array2(arr,num);
void bubble_sort(arr,num,input);
void insertion_sort(arr, num);
int main()
{
double array1[N];
double array2[N];
double array3[N];
for (int i = 0;i< N;i++)
{
array1[i] = rand() % 200 - 100;
array2[i] = rand() % 200 - 100;
array3[i] = rand() % 200 - 100;
}
print_array2(array1,N);
print_array2(array2,N);
print_array2(array3,N);
bubble_sort(array1,N,0);
bubble_sort(array2,N,0);
insertion_sort(array3,N);
print_array2(array1,N);
print_array2(array2,N);
print_array2(array3,N);
return 0;
}
void print_array2(arr, num)
{
for(int i=0;i<num;i++)
{
printf("%lf",arr[i]);
}
}
void bubble_sort(arr, num, input)
{
double temp;
for(int c =0; c< (num-1); c++)
{
for(int d =0; d < (num-c-1); d++)
{
if(input == 0) // in ascending
{
if (arr[d] > arr[d+1])
{
temp = arr[d];
arr[d] = arr[d+1];
arr[d+1] = temp;
}
}
else // in descending
{
if (arr[d] < arr[d+1])
{
temp = arr[d];
arr[d] = arr[d+1];
arr[d+1] = temp;
}
}
}
}
}
void insertion_sort(arr,num)
{
int c,d,temp;
for(c=0;c<num;c++)
{
d = c;
while(d > 0 && arr[d-1] > arr[d])
{
temp = arr[d];
arr[d] = arr[d-1];
arr[d-1] = temp;
d--;
}
}
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.