用ahkv2实现了几个常用的排序算法
冒泡排序:
BubbleSort(arr, function) {
loop arr.length - 1
loop arr.length - A_Index
if function(arr[A_Index], arr[A_Index + 1]) > 0
temp := arr[A_Index], arr[A_Index] := arr[A_Index + 1], arr[A_Index + 1] := temp
return arr
}
选择排序:
SelectionSort(arr, function) {
len := arr.Length
loop len - 1 {
min := A_Index, j := A_Index + 1
loop len - A_Index {
if function(arr[min], arr[j]) > 0
min := j
j++
}
if min != A_Index
temp := arr[min], arr[min] := arr[A_Index], arr[A_Index] := temp
}
return arr
}
插入排序:
InsertionSort(arr, function) {
i := 2, len := arr.Length
while i <= len {
temp := arr[j := i]
while j > 1 && function(arr[j - 1], temp) > 0
arr[j] := arr[j - 1], --j
arr[j] := temp, ++i
}
return arr
}
快速排序:
QuickSort(arr, function) {
if 2 > len := arr.Length
return arr
ranges := [1 | (len << 32)], ranges.Length := len, i := 2
while i > 1 {
range := ranges[--i]
if (start := range & 0xffffffff) >= (end := range >> 32)
continue
mid := arr[(start + end) / 2], left := start, right := end
loop {
while function(arr[left], mid) < 0
++left
while function(arr[right], mid) > 0
--right
if left <= right
temp := arr[left], arr[left] := arr[right], arr[right] := temp, left++, right--
} until left > right
if start < right
ranges[i++] := start | right << 32
if end > left
ranges[i++] := left | end << 32
}
return arr
}
参数说明:
- arr 一个数组
- function 自定义的排序函数对象,接受a, b两个参数,当a > b时返回正数,当a < b时返回负数,当a = b时返回0
示例1,按中文拼音排序:
arr := ["Cucumber", "Asparagus", "Broccoli", "张三", "李四", "王五", "1", "2", "3"]
MsgBox(JoinArray(arr))
BubbleSort(arr, CompareString) ; 冒泡排序, CompareString默认按拼音排序
MsgBox(JoinArray(arr))
CompareString(str1, str2, locale := "zh-CN", cmpFlags := 0) => DllCall("CompareStringEx", "wstr", locale, "uint", cmpFlags, "wstr", str1, "int", -1, "wstr", str2, "int", -1, "ptr", 0, "ptr", 0, "ptr", 0) - 2
JoinArray(arr, delimiter := "`n") {
res := ""
for i in arr
res .= i delimiter
return res
}
示例2,按数字大小排序:
arr := []
loop 10
arr.Push(Random(-10, 10))
MsgBox(JoinArray(arr))
newArr := QuickSort(arr.Clone(), (a, b) => a - b) ; 快速排序, arr.Clone() 复制数组,防止arr被修改, (a, b) => a - b 从小到大排序
MsgBox(JoinArray(newArr))
JoinArray(arr, delimiter := "`n") {
res := ""
for i in arr
res .= i delimiter
return res
}
声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。