i'm new here and c++. I want to do bubble sort and calculate the runtime of the function. This is what i have done. It gives me output of the same statements. I only need the last answer to display. Thank you.
void bubblesort(int n)
{
auto start_time = Clock::now();
int* arr = new int[n];
int* p;
for(int i=0; i<n; i++){
arr[i]=i+1;
}
int i, j;
bool swapped;
int comparisons=0;
for (i = 0; i < n; i++) {
swapped = false;
for (j = 0; j < n-i-1; j++)
{
comparisons++;
if (arr[j] > arr[j+1])
{
int temp = arr[j];
arr[j]=arr[j+1];
arr[j+1]=temp;
swapped = true;
}
//This is where i want to calculate the runtime but this will give output of many of this statement.
//I only want the last amount to be output
auto end_time = Clock::now();
std::cout << "Time difference: " << std::chrono::duration_cast<std::chrono::milliseconds>
(end_time - start_time).count() << " milliseconds" << std::endl;
}
if (swapped == false)
break;
}
cout << "Number of comparisons = " << comparisons << endl;
delete[] arr;
}
Aucun commentaire:
Enregistrer un commentaire