Java-排序算法-冒泡排序

时间:2023-03-09 05:02:52
Java-排序算法-冒泡排序

一、冒泡排序的原理

冒泡排序,就是从第一个元素开始,通过两两交换,使小的先冒出来,然后再走第二轮使次小的冒出来,直到最后一轮最大的冒出来,排序完成

二、冒泡排序的伪代码实现:

 bubblesort(A)
{
for i = 1 to length[A]
{
for j = length[A] to i+1
{
if A[j] < A[j-1]
{
exchane A[j] and A[j-1];
}
}
}
}

三、冒泡排序的Java源码实现

import java.util.Comparator;
public class BubbleSort { /**
* 定义一个泛型的冒泡排序method
* 学习如何用泛型和以及如何实现冒泡排序
* 泛型的类型不能是基础类型的(比如int,double,char等),必须得是引用类型的(比如Integer、Double、Character)
*/ public static <T> void bubbleSort(T[] t, Comparator<? super T> comparator){
T temp = t[0];
for(int i = 0; i < t.length-1; i ++)
{
for(int j = t.length-1; j >= i+1; j --)
if (comparator.compare(t[j-1], t[j]) > 0)
{
temp = t[j-1];
t[j-1] = t[j];
t[j] = temp;
}
}
} /**
* @param args
* main函数是用来做测试的。
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
Integer[] ints = {2, 0, 5, 23, 1, 4, 8, 56, 19};
bubbleSort(ints, new Comparator<Integer> () {
public int compare(Integer o1, Integer o2){
return o1.intValue() - o2.intValue();
}
});
for (int i:ints)
{
System.out.print(i + " ");
}
System.out.println();
} }

运行结果:

0 1 2 4 5 8 19 23 56 

四、复杂度分析

O(N^2)