home / study / engineering / computer science / computer science questions and a
ID: 3729736 • Letter: H
Question
home / study / engineering / computer science / computer science questions and answers / c++ help, attach source code and output. please put coding conventions to explain program
Your question has been posted.
We'll notify you when a Chegg Expert has answered. Post another question.
C++ help, attach source code and output. Please put coding conventions to explain program
Make sure to implement proper coding conventions to receive full credit. Execute each subtask and complete the analysis table below. Make sure source code and output are clearly visible. Functions or classes are ok, the time analysis after the successful implementation of each sort is critical to receiving the full credit. Task 2: Functions or classes are ok. Create an array that holds 1000 random floats between 1-1000 Implement insertion sort to sort the values in ascending order. Least Greatest Measure the time it takes to execute the sort in milliseconds. Please run the sort 3 times.Explanation / Answer
/*
To calculate time you need to put function call between start and end time of system.
So Took the current system time in a begin variable and called function and took the end time
in end_time variable after that I calculated time and printed.
I implemented insertion sort function.
Sample Output:
Time: 1.00 milliseconds*/
#include<iostream>
#include<stdlib.h>
#include<stdio.h>
#include <ctime>
using namespace std;
/* Function to sort an array using insertion sort*/
void insertionSort(float arr[], int size)
{
int i,j;
float temp;
//Loop on unsorted array
for(i=1; i<size; i++)
{
temp=arr[i];
j=i-1;
//Loop on sorted array and finding position to place number
while((temp<arr[j]) && (j>=0))
{
//Adjusting all greater elements then temp to the right
arr[j+1]=arr[j];
j=j-1;
}
//Placing new element at right palace
arr[j+1]=temp;
}
}
int main()
{
//Declaring array of float type
float arr[1000];
//Generating array of 1000 float value
for(int i=0;i<1000;i++)
{
arr[i]=((1000-1) * ((float)rand() / 1000)) + 1;
}
//Starting time
const clock_t begin_time = clock();
//Calling function
insertionSort(arr,1000);
//Ending times
const clock_t end_time = clock();
//Calculating time
//1000 is multiplied to convert seconds to milliseconds
float time=1000*float(end_time-begin_time)/CLOCKS_PER_SEC;
//Displaying time
printf("Time: %.2f milliseconds",time);
return 0;
}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.