排序算法——冒泡排序(Bubble Sort)
排序算法——冒泡排序(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 dofor j ? 0 to n-2-i doif A[j] > A[j+1] thenswap 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 methodpublic 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;}//Testpublic 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 shuaiw6@student.unimelb.edu.au
總結
以上是生活随笔為你收集整理的排序算法——冒泡排序(Bubble Sort)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 网页美学设计原则(上)
- 下一篇: 【新番尝鲜】秀逗魔导士E-revolut