先定义一个排序器接口IArraySorter:
1 package org.liws1.sort; 2 3 import java.util.Comparator; 4 5 /** 6 * 排序器接口 7 */ 8 public interface IArraySorter { 9 public <T extends Comparable<T>> void sort(T[] list); 10 public <T> void sort(T[] list, Comparator<T> comp); 11 }
再新建一个工具类ArraySorterUtils,用于提供对数组的排序功能(为了方便,全部实现升序),然后向工具类中添加冒泡排序实现。
冒泡排序的思路:共需最多length-1次冒泡,每次冒泡要将冒泡范围内的最大记录冒泡到最后一个位置。
代码如下:
1 package org.liws1.sort; 2 3 import java.util.Arrays; 4 import java.util.Comparator; 5 6 /** 7 * 数组的排序,这里统一做升序排序 8 */ 9 public class ArraySorterUtils { 10 11 private static <T> void swap(T[] datas, int i, int j) { 12 if (i == j) return; 13 T temp = datas[i]; 14 datas[i] = datas[j]; 15 datas[j] = temp; 16 } 17 18 /** 19 * 冒泡排序器 20 */ 21 public static class BubbleSorter implements IArraySorter { 22 23 @Override public <T extends Comparable<T>> void sort(T[] datas) { 24 // swapped用于标记一趟冒泡过程中是否有交换记录的操作;如果没有,说明排序已经完成,可以结束循环了。 25 boolean swapped = true; 26 for (int i = 0; i < datas.length - 1 && swapped; i++) { 27 swapped = false; 28 for (int j = 0; j < datas.length - 1 - i; j++) { 29 if (datas[j].compareTo(datas[j + 1]) > 0) { 30 swap(datas, j, j + 1); 31 swapped = true; 32 } 33 } 34 } 35 } 36 37 @Override public <T> void sort(T[] datas, Comparator<T> comparator) { 38 boolean swapped = true; 39 for (int i = 0; i < datas.length - 1 && swapped; i++) { 40 swapped = false; 41 for (int j = 0; j < datas.length -1 - i; j++) { 42 if (comparator.compare(datas[j], datas[j + 1]) > 0) { 43 swap(datas, j, j + 1); 44 swapped = true; 45 } 46 } 47 } 48 } 49 50 } 51 52 }
测试代码:
1 package org.liws1.sort; 2 3 import java.util.Arrays; 4 import org.junit.Test; 5 6 public class _Test { 7 8 private Integer[] datas = { 30, 1, 29, 2, 28, 3, 27, 4, 26, 5, 25, 6, 24, 7, 9 23, 8, 22, 9, 21, 10, 20, 19, 15, 18, 12, 17, 11, 16, 14, 13 }; 10 11 @Test public void testBubble(){ 12 new ArraySorterUtils.BubbleSorter().sort(datas); 13 System.out.println(Arrays.toString(datas)); 14 } 15 16 }// out:[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30]
原文地址:https://www.cnblogs.com/apeway/p/10817257.html
时间: 2024-10-10 09:44:47