算法步驟:java
1)比較相鄰的元素。若是第一個比第二個大,就交換他們兩個。算法
2)對每一對相鄰元素做一樣的工做,從開始第一對到結尾的最後一對。這步作完後,最後的元素會是最大的數。ide
3)針對全部的元素重複以上的步驟,除了最後一個。code
4)持續每次對愈來愈少的元素重複上面的步驟,直到沒有任何一對數字須要比較。排序
package com.sort.bubble.service; import java.util.Comparator; /** * 冒泡排序接口類 * @author huang * */ public interface BubbleSortService { public <T extends Comparable<T>> void sort(T[] list); public <T> void sort(T[] list, Comparator<T> comparator); }
package com.sort.bubble.service.impl; import java.util.Comparator; import com.sort.bubble.service.BubbleSortService; /** * 冒泡排序接口實現類 * @author huang * */ public class BubbleSortServiceImpl implements BubbleSortService { @Override public <T extends Comparable<T>> void sort(T[] list) { if(null != list && list.length > 1) { int len = list.length; boolean isSwaped = true; T temp = null; for(int i=0;i<len && isSwaped;i++) { isSwaped = false; for(int j=0;j<len-i;j++) { if(list[j].compareTo(list[j+1]) > 0) { temp = list[j]; list[j] = list[j+1]; list[j+1] = temp; isSwaped = true; } } } } } @Override public <T> void sort(T[] list, Comparator<T> comparator) { if(null != list && list.length > 1 && null != comparator) { int len = list.length; T temp = null; boolean isSwaped = true; for(int i=0;i<len && isSwaped;i++) { isSwaped = false; for(int j=0;j<len-i;j++) { if(comparator.compare(list[j], list[j+1]) > 0) { temp = list[j]; list[j] = list[j+1]; list[j+1] = temp; isSwaped = true; } } } } } }