常用排序算法之插入排序与希尔排序

来源:互联网 发布:淘宝店铺免费代码 编辑:程序博客网 时间:2024/04/30 04:26
'插入排序
Option Explicit

Dim Result, I
Dim TestData(100)
const N = 100

Randomize
For I = 0 To N - 1
TestData(I) 
= ROUND(RND() * 32768)
Next

'插入排序
Sub ISort(byRef Array, low, hi)
Dim i, j, t
For i = low+1 To hi
   t 
= Array(i)
   j 
= i - 1
   
Do
    
If j < low Then 
     
Exit Do
    
End If
    
If Array(j) > t Then
     
Array(j+1= Array(j)
     j 
= j - 1
    
Else
     
Exit Do
    
End If
   
Loop
   
Array(j+1= t
Next
End Sub

ISort TestData, 
0, N - 1

For I = 0 To N - 1
Result 
= Result & TestData(I) & VbTab
Next

MsgBox(Result)
'希尔排序
Option Explicit

Dim Result, I
Dim TestData(100)
const N = 100

Randomize
For I = 0 To N - 1
TestData(I) 
= ROUND(RND() * 32768)
Next

Sub SortWithStep(byRef Array, low, hi, stp)
Dim s, i, j, t
For s = 0 To stp-1
    
For i = s+low+stp To hi Step stp
           t 
= Array(i)
           j 
= i-stp
           
Do
                
If j < s+low Then 
                     
Exit Do
                
End If
                
If Array(j) > t Then
                     
Array(j+stp) = Array(j)
                     j 
= j - stp
                
Else
                     
Exit Do
                
End If
           
Loop
           
Array(j+stp) = t
    
Next
Next
End Sub

'希尔排序
Sub ShellSort(byRef Array, low, hi)
Dim Step
Step 
= Int((hi-low+1)/2+ 1
Do
    SortWithStep 
Array, low, hi, Step
    
If Step < 1 Then 
        
Exit Do
    
Else
        Step 
= Int(Step/2)
    
End If
Loop
End Sub

ShellSort TestData, 
0, N - 1

For I = 0 To N - 1
Result 
= Result & TestData(I) & VbTab
Next

MsgBox(Result)
 
原创粉丝点击