算法介绍:
789456进行排序,相邻的数字进行排序,如果前面的大则进行交换,否则不发生变化,再继续进行相邻的比较,一轮比较完成后获得最大值,下一轮需要比较的值就会少一个。分析下前面的例子:7小于8则没有变化,8小于9没有变化,9大于4位置互换784956,9大于5位置互换784596,9大于6则位置互换784569,获得最大值,后面继续进行比较位数少一位,直到比较完。
789456--->784569--->845679--->456789
动图演示:
代码演示:
package com.hy.sort.bubblesort; import lombok.Data; /** * @author hanyong * @date 2020/11/3 22:22 */ @Data public class Person implements Comparable<Person> { private int age; private String name; /** * 当前对象的年龄大则会返回大于0 * @param o * @return */ @Override public int compareTo(Person o) { return this.getAge() - o.getAge(); } } package com.hy.sort.bubblesort; import java.util.Arrays; /** * @author hanyong * @date 2020/11/3 22:27 */ public class BubbleSort { /** * 排序实现 * * @param comparables */ private void bubbleSort(Comparable[] comparables) { //需要参与排序的元素个数 for (int i = comparables.length - 1; i > 0; i--) { //当次比较的元素 for (int j = 0; j < i; j++) { if (isBigger(comparables[j], comparables[j + 1])) { exchange(comparables, j, j + 1); } } } } /** * 大于0说明c1大与c2 * * @param c1 * @param c2 * @return */ private boolean isBigger(Comparable c1, Comparable c2) { return c1.compareTo(c2) > 0; } /** * 交换数组对应索引的值 * * @param comparables * @param i * @param j */ private void exchange(Comparable[] comparables, int i, int j) { Comparable temp = comparables[i]; comparables[i] = comparables[j]; comparables[j] = temp; } public static void main(String[] args) { Person p1 = new Person(); p1.setName("张三"); p1.setAge(9); Person p2 = new Person(); p2.setName("李四"); p2.setAge(7); Person p3 = new Person(); p3.setName("王五"); p3.setAge(6); Comparable[] comparables = {p1, p2, p3}; BubbleSort bubbleSort = new BubbleSort(); bubbleSort.bubbleSort(comparables); System.out.println(Arrays.toString(comparables)); Integer[] numbs = {4, 3, 6, 8, 9, 10}; bubbleSort.bubbleSort(numbs); System.out.println(Arrays.toString(numbs)); } }
时间复杂度
按照最坏情况计算
654321
需要比较的次数:(n-1)+(n-2)+(n-3)+...+1=((n-1)+1)/2 * (n-1)/2=n2/4-n/4
需要交换的次数:(n-1)+(n-2)+(n-3)+...+1=((n-1)+1)/2 * (n-1)/2=n2/4-n/4
和为n2/2-n/2,根据时间复杂度计算规则有平方项线性阶忽略,最高次项常数忽略所以冒泡排序的时间复杂度为o(n2)
原文:https://www.cnblogs.com/yongzhewuwei/p/13923239.html