找回密码
 加入
搜索
查看: 2887|回复: 2

[效率算法] 一个将字符串排序为指定顺序的算法

  [复制链接]
发表于 2012-1-11 20:04:51 | 显示全部楼层 |阅读模式
本帖最后由 大绯狼 于 2012-1-11 20:07 编辑

由于工作中遇到一个问题 需要将字符串排序为指定格式,并且每一步只能交换相邻2个元素的位置,看看大家是否能有好的办法
例子如下
原字符串
[au3]abcdefghijklmnopqrstuvwxyz[/au3]
指定样式
[au3]qwertyuiopasdfghjklzxcvbnm[/au3]

允许使用UDF,但是排序部分必须每一步只交换相邻元素位置
先抛个砖,正常的排序方法,使用179步
[au3]#include <Array.au3>

Global $before, $after,$stepNum
$before = StringSplit("abcdefghijklmnopqrstuvwxyz", "", 2)
$after = StringSplit("qwertyuiopasdfghjklzxcvbnm", "", 2)
sort()
MsgBox(0,0,$stepNum)


Func sort()
        $stepNum=0
        $sIndex = 1
        For $i In $after
                $count = UBound($after) - 1
                $index = _ArraySearch($before, $i)
                For $j = $sIndex To $index
                        If ($index > 0 And $index <=$count) Then
                                $temp = $before[$index - 1]
                                $before[$index - 1] = $before[$index]
                                $before[$index] = $temp
                                $index -= 1
                                $stepNum+=1
                        EndIf
                Next
                $sIndex += 1
        Next
EndFunc  [/au3]
发表于 2012-1-12 10:27:57 | 显示全部楼层
貌似思路一样,都是笨方法
#include <Array.au3>

Global $before, $after, $stepNum = 0
$before = StringSplit("abcdefghijklmnopqrstuvwxyz", "", 2)
$after = StringSplit("qwertyuiopasdfghjklzxcvbnm", "", 2)
sort()
MsgBox(0, 0, $stepNum)
_ArrayDisplay($before)

Func sort()
        For $i = 0 To UBound($after) - 1
                $temp = $after[$i]
                $index = _ArraySearch($before, $temp)
                If $index > 0 And $index < UBound($before) Then
                        For $n = $index To $i + 1 Step -1
                                $stepNum += 1
                                _ArraySwap($before[$n], $before[$n - 1])
                        Next
                EndIf
        Next
EndFunc   ;==>sort

评分

参与人数 1金钱 +40 收起 理由
大绯狼 + 40 非常感谢~

查看全部评分

发表于 2012-1-12 15:40:53 | 显示全部楼层
既然说了是相邻两两交换,就只能冒泡了,这个冒泡还有冒的更快的啊?
您需要登录后才可以回帖 登录 | 加入

本版积分规则

QQ|手机版|小黑屋|AUTOIT CN ( 鲁ICP备19019924号-1 )谷歌 百度

GMT+8, 2024-4-27 17:27 , Processed in 0.080942 second(s), 24 queries .

Powered by Discuz! X3.5 Licensed

© 2001-2024 Discuz! Team.

快速回复 返回顶部 返回列表