i'm trying to keep track of how many comparisons and swaps my sorting algorithms are making. i know it's probably a variable referencing problem, but i can't seem to get it to work right. it's fine when i run only one of the sorts, but if i run both, moves comes out to 0. how can i fix this? here's a sample.

InsertionSort(myarray1, size1);
BubbleSort(myarray1, size1);


void InsertionSort(Item a[], int Numitems)
{
	int InsertItem, InnerCount, TempValue;
        int swaps = 0; int comparisons = 0;

	//move through list left to right
	for (InsertItem = 1; InsertItem < Numitems; InsertItem++)
	{
		//copy that value to a temp value
		TempValue = a[InsertItem];

		//move from that item to the left
		for (InnerCount = InsertItem - 1; InnerCount >= 0 &&
			TempValue < a[InnerCount]; InnerCount--)
		{
                        comparisons += 1;
			//move values to right
			a[InnerCount+1] = a[InnerCount];

		}
		//put insert value into correct spot
		a[InnerCount+1] = TempValue;
                swaps +=1;
	}
    for(int i=0; i<Numitems; i++)
            cout<<a[i]<<" " <<endl;
            cout<<"swaps = "<<swaps<<endl;
            cout<<"comparisons = "<<comparisons;
}


void BubbleSort(Item a[], int Numitems)
{
	int NumPasses;
	int InnerCount;
	Item TempValue;
        int swaps = 0; int comparisons = 0;

	//start outer loop
	for (NumPasses=0; NumPasses < Numitems-1; NumPasses++)
	{
		//start inner loop
		for (InnerCount=0; InnerCount < Numitems-1; InnerCount++)
		{
			//compare adjacent values
			if (a[InnerCount] > a[InnerCount+1])
			{
				//swap values
				TempValue = a[InnerCount];
				a[InnerCount] = a[InnerCount+1];
				a[InnerCount+1] = TempValue;
               swaps+=1;
			}
            comparisons += 1;
		}
	}
         for(int i=0; i<Numitems; i++)
            cout<<a[i]<<" " ;
            cout<<"swaps = "<<swaps<<endl;
            cout<<"comparisons = "<<comparisons<<endl;
}

>it's fine when i run only one of the sorts, but if i run both, moves comes out to 0.

If you've sorted the list, just how many swaps do you think you'd need to sort the list?

i'm not sure if i understand your question. of course after it's sorted there won't be any swaps needed. the part that i left out of the code is where i fill the array with random numbers (sorry). so, naturally, it would depend on the numbers & how mixed up in the array they are.


[edit] oh ok, i see what youre saying!!, since i've done the sort once, it's already sorted. duh! thanks.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.