10,000個くらいの数値なら一瞬でソートしてくれました。1,000,000個くらいになるとPCが少し固まりました。
ビッグデータなんてのが流行っていますが、データ件数が1,000,000を超えると処理に時間がかかって大変そうです。
ソースコードは、ご自由にご利用ください。ただし、趣味のプログラムなので、保証はありません。
Option Explicit
Public Sub test()
Dim i As Long
Dim N As Long
Dim num() As Long
Sheet1.Cells.ClearContents
N = 8
ReDim num(N - 1) As Long
For i = 0 To N - 1
num(i) = N * Rnd()
Next i
For i = 0 To N - 1
Sheet1.Cells(i + 1, 1) = num(i)
Next i
'sort_selection num, N
'sort_insert num, N
sort_quick num, 0, N - 1
For i = 0 To N - 1
Sheet1.Cells(i + 1, 2) = num(i)
Next i
End Sub
'選択ソート
'最小値を見つけて、小さい順に並べる
Public Sub sort_selection(num() As Long, N As Long)
Dim i As Long
Dim j As Long
Dim temp As Long
For i = 0 To N - 1
For j = i To N - 1
If num(j) < num(i) Then
temp = num(i)
num(i) = num(j)
num(j) = temp
End If
Next j
Next i
End Sub
'挿入ソート
'ソートされている部分に後ろから1つずつ値を挿入していく
Public Sub sort_insert(num() As Long, N As Long)
Dim i As Long
Dim j As Long
Dim temp As Long
For i = 0 To N - 1
temp = num(i)
For j = i To 1 Step -1
If temp < num(j - 1) Then
num(j) = num(j - 1)
Else
Exit For
End If
Next j
num(j) = temp
Next i
End Sub
'クイックソート
'pivotの値より大きいか小さいかで選り分ける
Public Sub sort_quick(num() As Long, n1 As Long, n2 As Long)
Dim i As Long
Dim j As Long
Dim pivot As Long
Dim temp As Long
'------------------------------
'すべての値が同じ場合は、ここで終了
For i = n1 To n2
If num(n1) <> num(i) Then Exit For
Next i
If i = n2 + 1 Then Exit Sub
'------------------------------
'pivotを選択 (pivotより小さい値が必ず存在する)
If num(n1) < num(i) Then
pivot = num(i)
Else
pivot = num(n1)
End If
'------------------------------
i = n1
j = n2
Do While True
Do While num(i) < pivot
i = i + 1
Loop
Do While pivot <= num(j)
j = j - 1
Loop
If j < i Then Exit Do
temp = num(i)
num(i) = num(j)
num(j) = temp
Loop
sort_quick num, n1, i - 1
sort_quick num, j + 1, n2
End Sub
0 件のコメント:
コメントを投稿