1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51
|
#include <iostream>
using namespace std;
struct Counts {
int comparisons;
int swaps;
int loops;
} counts = { 0, 0, 0 };
void gnomeSort(int* arr, int n) {
for (int index = 1; index < n; ) {
if (arr[index] >= arr[index - 1]) {
++counts.comparisons;
++index;
}
else {
++counts.swaps;
swap(arr[index], arr[index - 1]);
if (index > 1) --index;
}
++counts.loops;
}
}
void printArray(int* a, int n) {
while (n--) cout << *a++ << ' ';
cout << '\n';
}
int main(int argc, char** argv) {
int* a = nullptr;
int size = 0;
if (argc > 1) {
size = argc - 1;
a = new int[size];
for (auto b = a; *++argv; ) *b++ = stoi(*argv);
}
else {
size = 10;
a = new int[size];
auto b = a;
for (auto x: { 9, 3, 6, 8, 0, 1, 4, 7, 2, 5 }) *b++ = x;
}
gnomeSort(a, size);
cout << "After : ";
printArray(a, size);
cout << "comparisons: " << counts.comparisons << '\n';
cout << "swaps: " << counts.swaps << '\n';
cout << "loops: " << counts.loops << '\n';
}
| |