排序算法——冒泡排序(Bubble Sort)
算法簡介(Introduction)
Bubble sort is to compare adjacent elements of the list and exchange them as long as they are out of order. By repeatly compare and exchange, the largest element “bubbling up” go to last position in the list. In the second pass, the second largest element bubbles up to last second position. After n-1 passes, the list is sorted. In the ith pass, the state of list represented as follow:
(picture is from “Introduction to The Design and analysis of Algorithms” page 100)
示例(Example)
In the first pass, 100 bubbles up to last position.
僞代碼(Pseudocode)
function BubbleSort(A[0..n-1])
for i ⟵ 0 to n-2 do
for j ⟵ 0 to n-2-i do
if A[j] > A[j+1] then
swap A[j] and A[j+1]
基本屬性(property)
Input: an array A[0..n-1] of n orderable items.
Output: an array A[0..n-1] sorted in non-descending order.
In-place: YES. It only needs a constant amount O(1) of additional memory apace.
Stable: YES. Does not change the relative order of elements with equal keys.
時間複雜度(Time Complexity)
The input size is n.
the basic operation is key comparison A[j] > A[j+1].
The amount of times the basic operation executed is Cn.
適用情形(Suitable Situation)
Bubble sort is one of brute force sorting algorithms. It has simple idea that is to compare pair of adjacent elements and to swap. But it’s very slow and impractical for most problems. Even compared to insertion sort. It might be helpful when the input is sorted while having some occasional out-of-order elements.
Java Code
public class Sort{
//Bubble sort method
public static int[] bubbleSort(int[] A){
int i,j,tmp;
for(i=0;i<A.length-1;i++)
for(j=0;j<A.length-1-i;j++)
if(A[j] > A[j+1]){
tmp=A[j];
A[j]=A[j+1];
A[j+1]=tmp;
}
return A;
}
//Test
public static void main(String[] args){
int[] A={45,23,100,28,89,59,72};
int[] sortedA=Sort.bubbleSort(A);
for(int i=0;i<sortedA.length;i++)
System.out.print(A[i]+" ");
}
}
運行結果(Result)
23 28 45 59 72 89 100
寫在最後的話(PS)
Welcome any doubt. my email address is [email protected]