冒泡排序及优化

package defult;

import java.util.Arrays;

public class MaopaoSort {

static int[] array = {3,2,4,1,5,0};

public static void maopaoSort(int[] a)
{
//外层循环,是需要进行比较的轮数,一共进行5次即可
for(int i=0;i<a.length-1;i++)
{
//内存循环,是每一轮中进行的两两比较
for(int j=0;j<a.length-1;j++)
{
if(a[j] > a[j+1])
{
int temp = a[j];
a[j] = a[j+1];
a[j+1] = temp;
}
}
System.out.println("第"+(i+1)+"轮排序后的数组为: "+Arrays.toString(a));
}
}
//优化后
public static void maopaoSort2(int[] a)
{
//外层循环,是需要进行比较的轮数,一共进行5次即可
for(int i=0;i<a.length-1;i++)
{
//内存循环,是每一轮中进行的两两比较
//并且每一轮结束后,下一次的两两比较中可以少比较一次
for(int j=0;j<a.length-i-1;j++)
{
if(a[j] > a[j+1])
{
int temp = a[j];
a[j] = a[j+1];
a[j+1] = temp;
}
}
System.out.println("第"+(i+1)+"轮排序后的数组为: "+Arrays.toString(a));
}
}
static int[] array2 = {2,1,0,3,5,4};
public static void maopaoSort3(int[] a)
{
//外层循环,是需要进行比较的轮数,一共进行5次即可
for(int i=0;i<a.length-1;i++)
{
boolean flag = false;
//内存循环,是每一轮中进行的两两比较
for(int j=0;j<a.length-i-1;j++)
{
if(a[j] > a[j+1])
{
int temp = a[j];
a[j] = a[j+1];
a[j+1] = temp;
flag = true;
}
}
System.out.println("第"+(i+1)+"轮排序后的数组为: "+Arrays.toString(a));
if(flag == false)
{
System.out.println("本轮中的两两比较未发生元素互换,排序已经完成啦");
return;
}
}
}

public static void main(String[] args) {
maopaoSort3(array2);
}
}

posted on 2019-01-08 16:17  我是司  阅读(120)  评论(0)    收藏  举报

导航