# Thread: Insertion Sort Counting Comparisons

1. ## Insertion Sort Counting Comparisons

I'm trying to print the number of comparisons made when doing an insertion sort and the program compiles without a problem but after being prompted to type in however many numbers are necessary, when I input numbers nothing happens.

Code:
#include<iostream>
using namespace std;

#define MAX_LIST_LEN  100

int main(){

int    n,                    // list length
j,                    // loop control
L,                   // index of maximum element in unsorted section
a[MAX_LIST_LEN];   // array to be sorted
// Get values for n and list.
cout << "Enter list length (must be less than or equal to "
<< MAX_LIST_LEN << "): ";
cin  >> n;
cout << "Enter " << n << " numbers:" << endl;
int count = 0;
for (int L = 2; L<n; L++){
while (L <= n)
j = L;
while (j>=2
)a[j]<a[j-1];
a [j] == a[j-1];
j = j-1;
int L = L+1;
while (L>=1&&++count&&a[j]<a[j-1]
)cout << count << " ";

return(0);
}
}

2. How many different variables called L do you have?

How many do you need?

Which one is in scope at any given point in the code?

3. I cut the variables down to one but now the program won't compile at all:

Code:
#include<iostream>
using namespace std;

#define MAX_LIST_LEN  2000

int main(){

int    n,                    // list length
j,
L,                    // loop control
a[MAX_LIST_LEN];   // array to be sorted
int count = 0;
for (L = 2){
while (L <= n)
j = L;
while (j>=2
)a[j]<a[j-1];
a [j] == a[j-1];
j = j-1;
while (L>=1&&++count&&a[j]<a[j-1]
)cout << count << " ";

return(0);
}
}
When I try to compile I receive these errors:

Code:
InsertionSort.cpp:22: error: expected `;' before â)â token
InsertionSort.cpp:34: error: expected primary-expression before â}â token
InsertionSort.cpp:34: error: expected `;' before â}â token
InsertionSort.cpp:34: error: expected primary-expression before â}â token
InsertionSort.cpp:34: error: expected `)' before â}â token
InsertionSort.cpp:34: error: expected primary-expression before â}â token
InsertionSort.cpp:34: error: expected `;' before â}â token

4. > for (L = 2)

And I didn't mean you should blindly delete all declarations of L.
Renaming them to being loop, index, foo, bar, baz (or any other meaningful name) would perhaps have been more appropriate.

You need to think a bit about what you're trying to do here. Your program is just a mash of syntax at the moment. Even when you get it to compile, it's not likely to be doing what you want it to.