排序算法——冒泡排序(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
- 经典排序算法——冒泡排序Bubble sort
- 排序算法——冒泡排序(Bubble Sort)
- 冒泡排序(Bubble Sort)——排序算法
- 排序算法——冒泡排序(Bubble Sort)
- 算法--冒泡排序 Bubble Sort
- 经典排序算法 - 冒泡排序Bubble sort
- 经典排序算法 - 冒泡排序Bubble sort
- 经典排序算法 - 冒泡排序Bubble sort
- 经典排序算法 - 冒泡排序Bubble sort
- 经典排序算法 - 冒泡排序Bubble sort
- 经典排序算法 - 冒泡排序Bubble sort
- 经典排序算法 - 冒泡排序Bubble sort
- 经典排序算法 - 冒泡排序Bubble sort
- 经典排序算法 - 冒泡排序Bubble sort
- 经典排序算法 - 冒泡排序Bubble sort
- 排序算法-冒泡排序 Bubble Sort
- 经典排序算法 - 冒泡排序Bubble sort
- 经典排序算法 - 冒泡排序Bubble sort
- java Class类文件结构
- 找新朋友(欧拉函数)
- powerdesigner
- JS插件swiper的使用
- nmap
- 排序算法——冒泡排序(Bubble Sort)
- 搜素-P
- SAP HANA Odata的POST报错415 Unsupported Media
- Spring-data-jedis集群配置
- AlphaGo技术剖析:揭开围棋大脑的神秘面纱
- 【Unity3d】分享一些Unity3d的小技巧
- SAP HANA Odata的POST报错403 forbidden error
- 第三方支付“躺着赚钱”的时代开始终结
- Java二维数组计算集合(上下左右左斜右斜)