日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

排序算法——冒泡排序(Bubble Sort)

發布時間:2024/3/13 编程问答 42 豆豆
生活随笔 收集整理的這篇文章主要介紹了 排序算法——冒泡排序(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)的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。