1.基本思想
两两比较相邻的关键字,如果反序则交换,直到没有反序的记录为止。在这一过程中,较小的元素如同气泡般慢慢浮到上面
2.算法实现
正宗的冒泡算法
public static <AnyType extends Comparable<? super AnyType>> void bubblesort(AnyType[] a)
{
int i;
int j;
for(i = 0; i < a.length; i++)//第i个最小值
{
for(j = a.length - 1; j > i; j--)//j从后往前循环
{
if(a[j].compareTo(a[j - 1]) < 0)
swapReferences(a, j, j - 1 );
}
}
}
public static <AnyType> void swapReferences(AnyType[] a, int index1, int index2)//不需要继承Comparable,没用到比较方法
{
AnyType tmp = a[index1];
a[index1] = a[index2];
a[index2] = tmp;
}
- j一定是从后往前循环的,这样除了将第i个数上浮时,其他的较小数也会上浮
改进的冒泡算法
当序列在经过几次循环交换后已经有序,那么继续对有序部分的循环判断就是无意义的
如2,1,3,4,5,6
当i = 1时,交换了2和1的位置,此时数组已经有序
当i = 2时,此时我们在i = 1 时已经对6与5,5与4,4与3,3与2,进行了比较,不需要继续进行判断
为解决上述问题,我们使用标记变量来实现这个改进
public static <AnyType extends Comparable<? super AnyType>> void bubblesort(AnyType[] a)//改进的冒泡排序
{
int i;
int j;
boolean flag = true;
for(i = 0; i < a.length && flag; i++)//第i个最小值
{
flag = false;
for(j = a.length - 1; j > i; j--)//j从后往前循环
{
if(a[j].compareTo(a[j - 1]) < 0)
{
swapReferences(a, j, j - 1 );
flag = true;//如果有数据交换,则flag为true,否则flag为false,不进行循环
}
}
}
}
public static <AnyType> void swapReferences(AnyType[] a, int index1, int index2)//不需要继承Comparable,没用到比较方法
{
AnyType tmp = a[index1];
a[index1] = a[index2];
a[index2] = tmp;
}
3.算法分析
- 最好情况下(已经有序),只有n - 1次比较,时间复杂度为O(n),最坏情况下(逆序),需要进行1+2+…+ n-1次比较,并进行等数量级的移动,时间复杂度为O(n2)。因此,总时间复杂度为O(n2)
- 该算法不需要额外空间
- 空间复杂度为O(1)
- 算法是稳定的

6492

被折叠的 条评论
为什么被折叠?



