文章背景:冒泡排序(Bubble Sort)是排序算法里面比较简单的一个排序,在工作中用到的并不多,主要是想了解其中的算法思想,从而让我们的思维更加开阔。
基本原理:
代码实现:
Option Explicit
Sub BubbleSort()
Dim n As Integer, temp As Double
Dim i As Integer, j As Integer
n = Selection.Rows.Count
For i = 2 To n
For j = 2 To n - i + 2
If Selection.Cells(j - 1, 1) > Selection.Cells(j, 1) Then
temp = Selection.Cells(j, 1)
Selection.Cells(j, 1) = Selection.Cells(j - 1, 1)
Selection.Cells(j - 1, 1) = temp
End If
Next
Next
End Sub
运行效果:http://mpvideo.qpic.cn/0bf2nmaawaaagiabjhdibnqfa26dbnvqacya.f10002.mp4?dis_k=8ffa0f5de40a6d237938ebb0aa35a331&dis_t=1663655418&vid=wxv_1809326013609213954&format_id=10002&support_redirect=0&mmversion=false
参考资料:
[1] 算法之旅 | 冒泡排序法(https://zhuanlan.zhihu.com/p/28965019)
[2] Excel/VBA for Creative Problem Solving, Part 1(https://www.coursera.org/learn/excel-vba-for-creative-problem-solving-part-1/lecture/trGtF/putting-it-all-together-example-2)