Java-排序算法-冒泡排序
生活随笔
收集整理的這篇文章主要介紹了
Java-排序算法-冒泡排序
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
一、冒泡排序的原理
?冒泡排序,就是從第一個元素開始,通過兩兩交換,使小的先冒出來,然后再走第二輪使次小的冒出來,直到最后一輪最大的冒出來,排序完成
二、冒泡排序的偽代碼實現:?
1 bubblesort(A) 2 { 3 for i = 1 to length[A] 4 { 5 for j = length[A] to i+1 6 { 7 if A[j] < A[j-1] 8 { 9 exchane A[j] and A[j-1]; 10 } 11 } 12 } 13 }三、冒泡排序的Java源碼實現
?
import java.util.Comparator; public class BubbleSort {/*** 定義一個泛型的冒泡排序method* 學習如何用泛型和以及如何實現冒泡排序* 泛型的類型不能是基礎類型的(比如int,double,char等),必須得是引用類型的(比如Integer、Double、Character)*/public static <T> void bubbleSort(T[] t, Comparator<? super T> comparator){T temp = t[0];for(int i = 0; i < t.length-1; i ++){for(int j = t.length-1; j >= i+1; j --)if (comparator.compare(t[j-1], t[j]) > 0){temp = t[j-1];t[j-1] = t[j];t[j] = temp;}}}/*** @param args* main函數是用來做測試的。*/public static void main(String[] args) {// TODO Auto-generated method stubInteger[] ints = {2, 0, 5, 23, 1, 4, 8, 56, 19};bubbleSort(ints, new Comparator<Integer> () {public int compare(Integer o1, Integer o2){return o1.intValue() - o2.intValue();}});for (int i:ints){System.out.print(i + " ");}System.out.println();}}運行結果:
0 1 2 4 5 8 19 23 56四、復雜度分析
O(N^2)
轉載于:https://www.cnblogs.com/keke-xiaoxiami/p/4304841.html
總結
以上是生活随笔為你收集整理的Java-排序算法-冒泡排序的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: C++的new和delete
- 下一篇: Java-数据结构与算法-二分查找法