这是我做的冒泡排序,我想实现记录"关键字"的比较次数和移动次数,我想请问哪位高手知道该怎么加计数器?

来源:百度知道 编辑:UC知道 时间:2024/06/27 19:44:07
这是我的程序:
#include <iostream.h>
#include <stdlib.h>

void swap(int Array[],int i,int j)
{
int Temp=Array[i];
Array[i]=Array[j];
Array[j]=Temp;
}
void main()
{
int Array[3]={3,5,2};
for(int i=0;i<3;i++)
{
cout << Array[i] << " ";
}
cout << endl;
for( i=1;i<3;i++)
{
for(int j=2;j>=i;j--)
{
if(Array[j]<Array[j-1])
{
swap(Array,j,j-1);
}
}
}
cout << "The new sort is:"<< endl;
for( i=0;i<3;i++)
{
cout << Array[i] <<" ";
}
cout << endl;

}
指的是参加比较的数 在这里就是3 5 2 这几个数

for(int j=2;j>=i;j--)
{
if(Array[j]<Array[j-1])
{
swap(Array,j,j-1);
}
}
在这一段语句中,每一次进入for循环体都会首先执行if语句,所以把比较计数器加在for里面,if外面就行了;而移动语句是在if当中,所以把移动计数器加在if里面就行了!
下面是改过的代码:

#include <iostream.h>
#include <stdlib.h>

void swap(int Array[],int i,int j)
{
int Temp=Array[i];
Array[i]=Array[j];
Array[j]=Temp;
}

void main()
{
int moveTime=0;
int cmdTime=0;
int Array[3]={8,4,5};
for(int i=0;i<3;i++)
cout << Array[i] << " ";
cout << endl;
for( i=1;i<3;i++)
{
for(int j=2;j>=i;j--)
{
cmdTime++;
if(Array[j]<Array[j-1])
{
swap(Array,j,j-1);
moveTime++;
}
}
}
cout << "The new sort is:"<< endl;
for( i=0;i<3;i++)
cout << Array[i] <<" "<<e