1>
class maopao
{
static int count=0;
static void bubbleSort(int[] a)
{
for (int j = a.length - 1; j > 0; j--) // outer loop (backward)
for (int i = 0; i < j; i++) // inner loop (forward)
{ if (a[i] > a[i+1]) //Swap
{
a[i] = a[i] + a[i+1];
a[i+1] = a[i] - a[i+1];
a[i] = a[i] - a[i+1];
}
count++;
}
}
public static void main(String[] args)
{
int[] a = new int[]{9,8,5,4,2,0};
//int[] a = new int[]{9,8,7,6,5,4,3,2,1,0,11};
bubbleSort(a);
System.out.println("count&&&&"+count);
for (int i=0; i < a.length-1; i++)
{
System.out.print(a[i]+", ");
}
}
}
2>
class maopao4
{
public static void test1() //最普通的冒泡算法,需要比较(n-1)*(n-1)次
{
int[] iArray={9,8,5,4,2,0};
int k=0;
int icount=0;
for(int j=0;j<iArray.length-1;j++)
{
for(int i=0;i<iArray.length-1;i++)
{
if(iArray[i]>iArray[i+1])
{
k=iArray[i];
iArray[i]=iArray[i+1];
iArray[i+1]=k;
}
icount++;
}
}
System.out.println("共做比较次数: "+icount);
for(int i=0;i<iArray.length;i++)
{
System.out.print(" "+iArray[i]);
}
}
public static void test2() //稍微作了一下改进,加入一个布尔变量,当顺序已经排好后,就不用做额外的比较了
{
int[] iArray={9,8,5,4,2,0};
int k=0;
int icount=0;
boolean b=false;
for(int j=0;j<iArray.length-1;j++)
{
b=false;
for(int i=0;i<iArray.length-1;i++)
{
if(iArray[i]>iArray[i+1])
{
k=iArray[i];
iArray[i]=iArray[i+1];
iArray[i+1]=k;
b=true;
}
icount++;
}
if(!b) break;
}
System.out.println("\r\n\r\n共做比较次数: "+icount);
for(int i=0;i<iArray.length;i++)
{
System.out.print(" "+iArray[i]);
}
}
public static void main(String[] args)
{
test1();
test2();
}
}
posted on 2005-03-30 18:15
小力力力 阅读(547)
评论(0) 编辑 收藏 所属分类:
JAVA