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

来源:互联网 发布:html的sql注入 编辑:程序博客网 时间:2024/06/05 23:57

排序算法——冒泡排序(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 shuaiw6@student.unimelb.edu.au

原创粉丝点击