我是靠谱客的博主 顺心巨人,这篇文章主要介绍冒泡排序(加速),现在分享给大家,希望可以做个参考。

复制代码
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
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
package com.test; import java.util.Arrays; import java.util.Comparator; public class BubbleSort { private BubbleSort() { } // test public static void main(String[] args) { Integer[] list1 = new Integer[]{1, 5, 2, 4, 5, 6, 9, 10, 58, 32, 16, 3, -1, 8}; sort(list1, new Comparator<Integer>() { @Override public int compare(Integer t1, Integer t2) { if (t1 > t2) return 1; else if (t1 == t2) return 0; else return -1; } }); System.out.println(Arrays.toString(list1)); Integer[] list2 = new Integer[] {1, 5, 2, 4, 5, 6, 9, 10, 58, 32, 16, 3, -1, 8}; sort(list2); System.out.println(Arrays.toString(list2)); } //sort with Comparator public static <T> void sort(T[] list, Comparator<T> comparator) { boolean swap = true; // reduce sort time under some situation for (int i = 0, len = list.length; i < len - 1 && swap == true; i++) { swap = false;//if swap is false after inner loop, then the list is completely sorted for (int j = 0; j < len - i - 1; j++) { if (comparator.compare(list[j], list[j + 1]) > 0) { T temp = list[j]; list[j] = list[j + 1]; list[j+1] = temp; swap = true; } } } } // sort Comparable list public static <T extends Comparable<T>> void sort(T[] list) { boolean swap = true;// reduce sort time under some situation for (int i = 0, len = list.length; i < len - 1 && swap == true; i++) { swap = false;//if swap is false after inner loop, then the list is completely sorted for (int j = 0; j < len - i - 1; j++) { if (list[j].compareTo( list[j+1]) > 0) { T temp = list[j]; list[j] = list[j + 1]; list[j+1] = temp; swap = true; } } } } }

最后

以上就是顺心巨人最近收集整理的关于冒泡排序(加速)的全部内容,更多相关冒泡排序(加速)内容请搜索靠谱客的其他文章。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(74)

评论列表共有 0 条评论

立即
投稿
返回
顶部