开发者

What's wrong with this mergesort?

I'm trying to implement mergesort in Coldfusion, but it is spitting out incorrect results, code:

<cffunction name="mergeSort" hint="Sorts arrays of structs">
<cfargument name="arr" type="Array" required="yes">

<cfif Arraylen(arr) LTE 1>
   <cfreturn arr />
</cfif>

<cfset left_ = ArrayNew(1)>
<cfset right_ = ArrayNew(1)>
<cfset mid_ = Int(Arraylen(arr) / 2)>

<cfloop index="i" from="1" to="#mid_#">
   <cfset arrayAppend(left_, arr[i])>
</cfloop>

<cfloop index="j" from="#mid_+1#" to="#ArrayLen(arr)#">
   <cfset arrayAppend(right_, arr[j])>
</cfloop>


<cfreturn merge( mergeSort(left_), mergeSort(right_) )>

</cffunction>



<cffunction name="merge" hint="Merges two arrays">
<cfargument name="left_" required="yes" type="Array">
<cfargument name="right_" required="yes" type="Array">

<cfset result = ArrayNew(1)>

<cfloop condition="ArrayLen(left_) GT 0 AND ArrayLen(right_) GT 0">
   <cfif left_[1].attr3 LTE right_[1].attr3>
       <cfset arrayAppend(result, left_[1])>
       <cfset arrayDeleteAt(left_, 1)>
   <cfelse>
       <cfset arrayAppend(result, right_[1])>
       <cfset arrayDeleteAt(right_, 1)>
   </cfif>
</cfloop>

<cfif ArrayLen(left_) GT 0>
   <cfloop array="#left_#" index="v">
       <cfset ArrayAppend(result, v)>
   </cfloop>
</cfif>
开发者_开发技巧
<cfif ArrayLen(right_) GT 0>
   <cfloop array="#right_#" index="v">
       <cfset ArrayAppend(result, v)>
   </cfloop>
</cfif>

<cfreturn result />

</cffunction>

It's sorting an array of structs, on the struct key called "attr3". What happens is that it splits the lists correctly, it seems, but then continues to attach the same list to the resultset. So, for example, if I have left_.attr3 as "Title" and right_.attr3 as "Another", the result ends up being "Title", "Another", "Another", "Another" .. etc.


Have you looked at How to sort an array of structs in ColdFusion ?

btw, pls var scope all your variables!

btw, you can join arrays with Java Join Two Arrays in ColdFusion

btw, you can use mid_ = Arraylen(arr) \ 2 for integer div

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜