0

Hey guys, I was curious if I could get some help with these two pieces of code. What I'm trying to do is count the number of comparisons and moves there are in each type of sort, now I'm not a super programmer but I kinda know my way around the language.

What I'm having problems with is putting the counters in the correct spot. Any and all help is appreciated! =)

**INSERTION SORT CODE:**

```
#include "list.cpp"
using namespace std;
void insertionSort(ListType list, int n);
int compare = 0;
int move = 0;
int main()
{
ListType list;
int n;
int num;
cout << "How many trials do you want to perform: ";
cin >> num;
cout << "What is the size of the list you are testing: ";
cin >> n;
for (int i = 1; i <= num; i++)
{
fillList(list, n);
insertionSort(list, n);
}
cout << "comparisons: " << compare/num << "\nmoves: "
<< move/num << endl;
fillList(list, n);
insertionSort(list, n);
system("PAUSE");
return 0;
}
void insertionSort(ListType list, int n)
{
int j, k;
element itemToInsert;
bool stillLooking;
// On the kth pass, insert item k into its correct position among
// the first k entries in array. }
for (k = 1; k < n; ++k)
{
// Walk backwards through list, looking for slot to insert A[K]
itemToInsert = list[k];
j = k - 1;
stillLooking = true;
while ((j >= 0) && stillLooking )
{
compare++;//------------------------------------>FIX
if (itemToInsert < list[j])
{
move++;
list[j + 1] = list[j];
--j;
}
else
stillLooking = false;
// Upon leaving loop, J + 1 is the index
// where itemToInsert belongs
list[j + 1] = itemToInsert;
}
}
}
```

----------------------------------------------------------------------------------------------------------------------------------------------------

**SELECTION SORT CODE:**

```
#include "list.cpp"
#include "boolean.h"
using namespace std;
void selectionSort(ListType list, int n);
int compare = 0;
int move = 0;
int main()
{
ListType list;
int n;
int num;
cout << "How many trials do you want to perform: ";
cin >> num;
cout << "What is the size of the list you are testing: ";
cin >> n;
for (int i = 1; i <= num; i++)
{
fillList(list, n);
selectionSort(list, n);
}
cout << "comparisons: " << compare/num << "\nmoves: "
<< move/num << endl;
fillList(list, n);
selectionSort(list, n);
system("PAUSE");
return 0;
}
void selectionSort(ListType list, int n)
{
int index;
element temp;
// Make n - 1 passes through successively smaller segments
for (int j = 0; j < n - 1; ++j)
{
index = j;
for (int k = j + 1; k < n; ++k) // Find index of the smallest element
{
compare++;
if (list[k] < list[index])
index = k;
if (index != j)
{
move ++; //--------------------------> FIX
temp = list[index]; // Exchange must be made
list[index] = list[j];
list[j] = temp;
//printList(list, n);
}
}
}
}
```

*Edited 6 Years Ago by Kayano*: n/a