Java數據構造及算法實例:冒泡排序 Bubble Sort。本站提示廣大學習愛好者:(Java數據構造及算法實例:冒泡排序 Bubble Sort)文章只能為提供參考,不一定能成為您想要的結果。以下是Java數據構造及算法實例:冒泡排序 Bubble Sort正文
/**
* 冒泡排序估量是每本算法書本都邑提到的排序辦法。
* 它的根本思緒是對長度為N的序列,用N趟來將其排成有序序列。
* 第1趟將最年夜的元素排在序列尾部,第2趟將第2年夜的元素排在倒數第二的地位,
* 即每次把未排好的最年夜元素冒泡到序列最初端。
* 該排序辦法現實上分為兩重輪回,外層輪回:待排元素從數組的第1個元素開端。
* 內層輪回:待排元素從數組的第1個元素開端,直到數組尾端未排過的元素。
* 在內輪回中,假如碰到後面元素比厥後的元素年夜就交流這兩個元素的地位。
* 因而可知冒泡排序的龐雜度是O(n^2)
*/
package al;
public class BubbleSort {
/*
* 冒泡排序 Java說話編寫,可以直接運轉 輸出:n個數<a1,a2,,an>
* 輸入:輸出序列的一個分列<a1',a2',,an'>,個中a1'<=a2'<=<=an' 待排的數也稱為key 龐雜度:O(n^2) 輸入成果:9
* 10 14 14 21 43 50 77 例子:高矮個站隊
*/
public static void main(String[] args) {
BubbleSort bubbleSort = new BubbleSort();
int[] elements = { 14, 77, 21, 9, 10, 50, 43, 14 };
// sort the array
bubbleSort.sort(elements);
// print the sorted array
for (int i = 0; i < elements.length; i++) {
System.out.print(elements[i]);
System.out.print(" ");
}
}
/**
* @author
* @param array
* 待排數組
* @return void
*/
public void sort(int[] array) {
int i, j;
int tmp;
for (i = 0; i <= (array.length - 1); i++) { // outer loop
for (j = 0; j < (array.length - 1 - i); j++) { // inner loop
if (array[j] > array[j + 1]) {
tmp = array[j];
array[j] = array[j + 1];
array[j + 1] = tmp;
}
}
}
}
}