-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
guohiu8
committed
Apr 3, 2017
1 parent
877faf3
commit 066f803
Showing
2 changed files
with
79 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,79 @@ | ||
# 冒泡排序 | ||
|
||
冒泡排序(Bubble Sort)也是一种简单直观的排序算法。它重复地走访过要排序的数列,一次比较两个元素,如果他们的顺序错误就把他们交换过来。走访数列的工作是重复地进行直到没有再需要交换,也就是说该数列已经排序完成。这个算法的名字由来是因为越小的元素会经由交换慢慢“浮”到数列的顶端。 | ||
|
||
作为最简单的排序算法之一,冒泡排序给我的感觉就像 Abandon 在单词书里出现的感觉一样,每次都在第一页第一位,所以最熟悉。冒泡排序还有一种优化算法,就是立一个 flag,当在一趟序列遍历中元素没有发生交换,则证明该序列已经有序。但这种改进对于提升性能来说并没有什么太大作用。 | ||
|
||
|
||
## 1. 算法步骤 | ||
|
||
1. 比较相邻的元素。如果第一个比第二个大,就交换他们两个。 | ||
|
||
2. 对每一对相邻元素作同样的工作,从开始第一对到结尾的最后一对。这步做完后,最后的元素会是最大的数。 | ||
|
||
3. 针对所有的元素重复以上的步骤,除了最后一个。 | ||
|
||
4. 持续每次对越来越少的元素重复上面的步骤,直到没有任何一对数字需要比较。 | ||
|
||
|
||
## 2. 动图演示 | ||
|
||
![动图演示](res/bubbleSort.gif) | ||
|
||
|
||
## 3. 什么时候最快 | ||
|
||
当输入的数据已经是正序时(都已经是正序了,我还要你冒泡排序有何用啊)。 | ||
|
||
|
||
## 4. 什么时候最慢 | ||
|
||
当输入的数据是反序时(写一个 for 循环反序输出数据不就行了,干嘛要用你冒泡排序呢,我是闲的吗)。 | ||
|
||
|
||
## 5. JavaScript 代码实现 | ||
|
||
```js | ||
function bubbleSort(arr) { | ||
var len = arr.length; | ||
for (var i = 0; i < len - 1; i++) { | ||
for (var j = 0; j < len - 1 - i; j++) { | ||
if (arr[j] > arr[j+1]) { // 相邻元素两两对比 | ||
var temp = arr[j+1]; // 元素交换 | ||
arr[j+1] = arr[j]; | ||
arr[j] = temp; | ||
} | ||
} | ||
} | ||
return arr; | ||
} | ||
``` | ||
|
||
|
||
|
||
## 6. Python 代码实现 | ||
|
||
```python | ||
def bubbleSort(arr): | ||
for i in range(1, len(arr)): | ||
for j in range(0, len(arr)-i): | ||
if arr[j] > arr[j+1]: | ||
arr[j], arr[j + 1] = arr[j + 1], arr[j] | ||
return arr | ||
``` | ||
|
||
## 7. Go 代码实现 | ||
|
||
```go | ||
func bubbleSort(arr []int) []int { | ||
length := len(arr) | ||
for i := 0; i < length; i++ { | ||
for j := 0; j < length-1-i; j++ { | ||
if arr[j] > arr[j+1] { | ||
arr[j], arr[j+1] = arr[j+1], arr[j] | ||
} | ||
} | ||
} | ||
return arr | ||
} | ||
``` |
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.