Counting sorting operations
Hi,
I'm trying to count the number of operations it takes a certain sorting algorighm (in this case a shell sort) to sort arrays of different sizes (numbers in the arrays are randomly generated).
Here is my code:
Code:
#include <iostream>
#include <string>
#include <cmath>
#include <fstream>
#include <iomanip>
#include <stdlib.h>
#include <time.h>
using namespace std;
void fill_array(int A[], int size);
int shell_sort(int A[], int size);
void print_array(int A[], int size);
int main()
{
const int size = 10000;
int A [size];
int B [21] = {1,2,3,4,5,6,7,8,9,10,20,30,40,70,100,200,300,500,1000,2000,5000};
int new_size = 0;
srand ((unsigned int)time((time_t)0));
for (int i = 0; i < 21; i++)
{
new_size = B[i];
fill_array(A, new_size);
shell_sort(A, new_size);
//int count = shell_sort(A, new_size);
//cout<<count<<endl;
}
return 0;
}
int shell_sort(int A[], int size)
{
int count = 0;
int i, j, increment, temp;
increment = size / 2;
while (increment > 0)
{
for (i = increment; i < size; i++)
{
j = i; count++;
temp = A[i]; count++;
while ((j >= increment) && (A[j-increment] > temp))
{
A[j] = A[j - increment]; count++;
j = j - increment; count++;
}
A[j] = temp; count++;
}
if (increment == 2)
increment = 1 && count++;
else
increment = (int) (increment / 2.2) && count++;
}
cout.width(4);
cout<<size<<": ";
cout<<count<<endl;
return count;
}
void fill_array(int A[], int size)
{
int first_rand = 0;
while(first_rand < size)
{
A[first_rand] = rand() % 1000;
first_rand++;
}
}
The problem:
If i print the output of the number of operations (count) in the for loop in main, i get results such as these (The left column is the size of the array, and the right column is how many operations it takes to sort the array):
Code:
1: 0
2: 3
3: 6
4: 16
5: 22
6: 25
7: 31
8: 34
9: 40
10: 43
20: 88
30: 133
40: 178
70: 313
100: 448
200: 898
300: 1348
500: 2248
1000: 4498
2000: 8998
5000: 22498
Now, if i print count and the end of the sorting function, i get results such as these:
Code:
1: 0
2: 3
3: 10
4: 18
5: 30
6: 39
7: 43
8: 56
9: 70
10: 61
20: 220
30: 427
40: 692
70: 1735
100: 3730
200: 15362
300: 31148
500: 85822
1000: 338354
2000: 1341068
5000: 8419422
So, when i print count in the sorting function, the numbers are alot higer than when count is printed in the for loop in main. So, i'm not sure what is going on, and which count is correct.
*Note, when i change where i output count (in main or in the sorting function) i comment out the other count.