package sort.bubble;
public class Bubble {
// 对数组a的元素进行排序
public static void sort(Comparable[] a) {
for (int i = a.length - 1; i > 0; i--) {
for (int j = 0; j < i; j++) {
// 比较j和j+1处的值
if (greater(a[j], a[j + 1])) {
exch(a, j, j + 1);
}
}
}
}
// 比较元素v是否大于元素w
private static boolean greater(Comparable v, Comparable w) {
return v.compareTo(w) > 0;
}
// 数组元素i和j互相交换位置
private static void exch(Comparable[] a, int i, int j) {
Comparable temp;
temp = a[i];
a[i] = a[j];
a[j] = temp;
}
}
构造方法:Bubble():创建Bubble对象
成员方法:先写greater()方法 ,比较两个元素的大小
再写exch()方法,如果使两个元素交换位置
最后写sort()方法,先确定有多少元素参与排序,再利用for循环从头往前一个个 使用greater()比较大小,最后使用exch()将其交换位置。
package sort.bubble;
import java.util.Arrays;
public class BubbleTest {
public static void main(String[] args) {
Integer[] arr = {4, 43, 34, 4, 2, 4, 5, 6};
Bubble.sort(arr);
System.out.println(Arrays.toString(arr));
}
}
新建数组arr时使用了int,导致调用sort()报错
解决方法:使用Interger,Integer是java为int提供的封装类。
时间复杂度分析
最坏的情况下:比较次数加上交换次数为(n的二次方减去n)
时间复杂度就是O(N^2)