|
本帖最后由 hyefeifei 于 2013-12-1 21:20 编辑
中间可以不是P,但必须是一位,右边数字在一到四位之间
简单解释一下,就是把你的字符串,转换为数字,加上一个小数,保证唯一
再用快速排序法排序,然后用字典取回,不用字典,在快递排序法里加个输出数组参数
存储位置也可,这里用字典法- Sub Test()
- Dim arr, i&, str As String, strte, d, brr()
- Set d = CreateObject("Scripting.Dictionary")
- arr = Range("a2:a" & Cells(Rows.Count, "a").End(xlUp).Row)
- For i = 1 To UBound(arr)
- str = Val(Right(arr(i, 1), Len(arr(i, 1)) - 2))
- str = str & Format(Right(arr(i, 1), Len(arr(i, 1)) - 3 - Len(str)), "0000")
- strte = Asc(Left(arr(i, 1), 1)) * Asc(Mid(arr(i, 1), 1, 1)) & Format(str, "0000000") '至此把字符串转为数字
- strte = CDbl(strte) '转为双精度数字
- strte = strte + i / 10000 '加上一小数,保证数字唯一性
- d(strte) = arr(i, 1) '存到字典里
- arr(i, 1) = strte '把数组转为数值数组
- Next
- QSort arr '快速排序
- ReDim brr(1 To UBound(arr), 0)
- For i = 1 To UBound(arr) '取回排序结果
- brr(i, 0) = d(arr(i, 1))
- Next
- Range("c2").Resize(UBound(arr)) = brr
- End Sub
- '快速排序法(当然可用其他如冒泡之类),如主程序不用字典,可在此排序法上加一输出参数,存储元素位置
- Sub QSort(var As Variant, Optional iLeft As Long, Optional iRight As Long)
- Dim i&, j&, vTemp1, vTemp2, iMid&, Temp
- If IsMissing(iLeft) Then iLeft = LBound(var)
- If IsMissing(iRight) Then iRight = UBound(var)
- If iLeft < iRight Then
- iMid = (iLeft + iRight) \ 2
- vTemp1 = var(iMid, 1)
- i = iLeft
- j = iRight
- Do
- vTemp2 = var(i, 1)
- Do While vTemp2 < vTemp1
- i = i + 1
- vTemp2 = var(i, 1)
- Loop
- vTemp2 = var(j, 1)
- Do While vTemp2 > vTemp1
- j = j - 1
- vTemp2 = var(j, 1)
- Loop
- If i <= j Then
- Temp = var(i, 1): var(i, 1) = var(j, 1): var(j, 1) = Temp
- i = i + 1
- j = j - 1
- End If
- Loop Until i > j
- Call QSort(var, iLeft, j)
- Call QSort(var, i, iRight)
- End If
- End Sub
复制代码
排序.rar
(12.49 KB, 下载次数: 12)
|
|