算法步骤: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; } } } } } }