Hello! So here is a question. I have to count the number of arithmetic operations when given an array to sort A(4,2,5,3,1). SO N=5
So I am just trying to figure it out through these nested loops.
i =1 : 1 time
i < n-1 : 4 time
i++ : 5 times
operation 1+4+5 = 10
Same with the second loop
operations in second loop = 10
So overall 10 + 10 + 9= 29 arithmetic operations.
I am not sure about if(A[j] > A(j+1)). Will they count?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
Fastsort(A.n)
{
for( i = 1 ; i < n-1 ; i++)
{
for( j = 0 ; j < n-1 ; j++)
{
if(A[j] > A(j+1))
{
swap (A[j] < A[j+1])// this function needs no improvement and uses 9
operations
}
}
}
}
Besides being horribly misnamed, the algorithm is wrong since the outer loop needs to go n times, not n - 1 times. So it's either for(i = 1; i < n; ++i) or for(i = 0; i < n-1; ++i)
With that correction, here's the operation counts:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
Fastsort(A, n)
{
// 1 5 4
for (i = 1; i < n; i++)
{
// 4 20 16
for (j = 0; j < n-1; j++)
{
// 16
if (A[j] > A[j+1])
{
swap(A[j], A[j+1]) // perhaps 8 * 9 = 72
}
}
}
}
So that's a total of 66 ops without counting swap. If we need to count the "9 operations" in the swap function then we could assume it runs about half the time, so (16/2)*9 = 72 and 66 + 72 = 138 operations.
#include <iostream>
#include<algorithm>
usingnamespace std;
int main() {
int a[] = { 4,2,5,3,1 };
for (int i = 0; i<5; i++) {
auto min = min_element(begin(a) + i, end(a));
iter_swap(begin(a) + i, min);
}
for (int i = 0; i < 5; i++) {
cout << a[i] << "\n";
}
}