TA的每日心情 | 开心 2021-3-12 23:18 |
---|
签到天数: 2 天 [LV.1]初来乍到
|
- 冒泡排序,虽然是简单的东西,但是还是写一写。
- 这个是基本类型int的数组版的:
- public static void sort(int[] array) {
- if (array == null) {
- throw new NullPointerException("数组对象为空!");
- }
-
- if (array.length == 0) {
- return;
- }
-
- int temp = 0;
- for (int i = 0; i < array.length; i++) {
- for (int j = array.length - 1; j > i; j--) {
- if (array[j - 1] > array[j]) {// 从大到小排序则把大于号改成小于号
- temp = array[j];
- array[j] = array[j - 1];
- array[j - 1] = temp;
- }
- }
- }
- }
- 这个是引用类型的泛型数组版的:
-
- public static
-
- void sort(T[] array) {
- if (array == null) {
- throw new NullPointerException("数组对象为空!");
- }
-
- if (array.length == 0) {
- return;
- }
-
- Class[] interfaces = array.getClass().getComponentType().getInterfaces();
-
- boolean canCompare = false;
-
- for (Class i : interfaces) {// 检查数组中的元素是否实现了java.lang.Comparable接口
- if (i == Comparable.class) {
- canCompare = true;
- break;
- }
- }
-
- if (!canCompare) {
- throw new IllegalArgumentException("数组中的元素必须实现java.lang.Comparable接口,否则无法排序!");
- }
-
- T[] tempArray = array.clone();// 使用克隆对象是为了出现异常时还原数组中原来的顺序
-
- T temp = null;
- for (int i = 0; i < tempArray.length; i++) {
- for (int j = tempArray.length - 1; j > i; j--) {
- T prev = tempArray[j - 1];
- T next = tempArray[j];
- if (prev == null || next == null) {
- throw new NullPointerException("数组中有空元素,无法排序!");
- }
- if (((Comparable)prev).compareTo(next) > 0) {// 从大到小排序则把大于号改成小于号
- temp = tempArray[j];
- tempArray[j] = tempArray[j - 1];
- tempArray[j - 1] = temp;
- }
- }
- }
-
- System.arraycopy(tempArray, 0, array, 0, tempArray.length);// 确保无异常发生再将排好序的克隆数组拷贝回原数组
- }
-
复制代码
源码下载:http://file.javaxxz.com/2014/10/28/235535859.zip |
|