1、Java语言实现
抽象类
public abstract class Sorter { public abstract void sort(int [] array); }
实现类
public class BubbleSorter extends Sorter { @Override public void sort(int[] array) { int temp;//用于交换数据的暂存单元 for (int i = array.length - 1; i >= 0; i--) {//将数组的最大索引视为“水面” //数组的最小索引视为“水底”,“气泡”从“水底”向“水面”上浮 //因为i每减少一个,就有一个“气泡”上浮到最终位置,所以只需要对1到i之间的元素进行交换排序即可。 for (int j = 1; j <= i; j++) { if (array[j - 1] > array[j]) {//如果上浮过程中发现比当前元素小的,就交换 temp = array[j - 1]; array[j - 1] = array[j]; array[j] = temp; } } } } }
测试
public class Test { public static void main(String[] args) { int[] arr = {94, 12, 34, 76, 26, 9, 0, 37, 55, 76, 37, 5, 68, 83, 90, 37, 12, 65, 76, 49}; //Sorter sorter = new QuickSorter(); Sorter sorter = new BubbleSorter(); sorter.sort(arr); System.out.println(Arrays.toString(arr)); } }
2、python语言实现
from abc import abstractmethod, ABCMeta class Sorter: __metaclass__ = ABCMeta @abstractmethod def sort(self, array): pass class BubbleSorter(Sorter): def sort(self, array): length = len(array) i = length - 1 while i >= 0: j = 1 while j <= i: # 上浮过程中,如果发现比当前元素小的,就进行交换 if array[j - 1] > array[j]: array[j - 1], array[j] = array[j], array[j - 1] j = j + 1 i = i - 1 if __name__ == '__main__': arr = [5, 4, 2, 1, 3] print(arr) bubbleSorter = BubbleSorter() bubbleSorter.sort(arr) print(arr)