他山之石——使用VBA演示排序算法-Part1(冒泡排序法和选择排序法)

程序=算法+数据结构

软件=程序+文档

我的理解,算法就是解决问题的方法和步骤,因为这世界充满了问题,所以可以说,算法无处不在。

Option Explicit

Sub 冒泡排序()
 Dim arr, temp, x, y, t, k
 t = Timer
 arr = Range("a1:a10")
 For x = 1 To UBound(arr) - 1
   For y = x + 1 To UBound(arr) '只和当前数字下面的数进行比较
     If arr(x, 1) > arr(y, 1) Then '如果它大于它下面某一个数字
       temp = arr(x, 1)
       arr(x, 1) = arr(y, 1)
       arr(y, 1) = temp
     End If
       
   Next y
 Next x
 Range("b3").Resize(x) = ""
 Range("b3").Resize(x) = arr
 'Range("b2") = Timer - t
 MsgBox k
End Sub


Sub 冒泡排序演示()
 Dim arr, temp, x, y, t, k
 For x = 1 To 9
                         Range("a" & x).Interior.ColorIndex = 3
   For y = x + 1 To 10  '只和当前数字下面的数进行比较
                         Range("a" & y).Interior.ColorIndex = 4
     If Cells(x, 1) > Cells(y, 1) Then '如果它大于它下面的某一个数字
       temp = Cells(x, 1)
       Cells(x, 1) = Cells(y, 1)
       Cells(y, 1) = temp
2     End If
                         Range("a" & y).Interior.ColorIndex = xlNone
   Next y
                         Range("a" & x).Interior.ColorIndex = xlNone
                         
 Next x

End Sub
Option Explicit


Sub 选择排序()
  Dim arr, temp, x, y, t, iMax, k, k1, k2
  t = Timer
  arr = Range("a1:a10")
  For x = UBound(arr) To 1 + 1 Step -1
     iMax = 1 '最大的索引
     For y = 1 To x
          If arr(y, 1) > arr(iMax, 1) Then iMax = y
     Next y
     temp = arr(iMax, 1)
     arr(iMax, 1) = arr(x, 1)
     arr(x, 1) = temp
  Next x
  
  'Range("c3").Resize(UBound(arr)) = ""
  'Range("c3").Resize(UBound(arr)) = arr
  'Range("c2") = Timer - t
  'MsgBox k1
End Sub

Sub 选择排序单元格演示()
  Dim arr, temp, x, y, t, iMax, k, k1, k2

  For x = 10 To 2 Step -1
     iMax = 1
                       Range("a" & x).Interior.ColorIndex = 3
     For y = 1 To x
                       Range("a" & y).Interior.ColorIndex = 4
          If Cells(y, 1) > Cells(iMax, 1) Then
                       Range("a" & iMax).Interior.ColorIndex = xlNone
           iMax = y
          End If
                       Range("a" & y).Interior.ColorIndex = xlNone
                       Range("a" & iMax).Interior.ColorIndex = 6
                       
     Next y
     temp = Cells(iMax, 1)
     Cells(iMax, 1) = Cells(x, 1)
     Cells(x, 1) = temp
     Range("a" & x).Interior.ColorIndex = xlNone
     Range("a" & iMax).Interior.ColorIndex = xlNone
  Next x

End Sub
    


  • 0
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值