Solved

Sorting a 2 dimension array??

Posted on 2001-08-02
7
385 Views
Last Modified: 2013-12-24
Hello everyone,

  Is there a way to sort a 2 dimension array other then hard coding? I've tried with ArraySort, but it doesn't work with complex variable. So basically, is there a way around this or will I have to code it? I only want to sort on the first dimension of the array.

  Any idea how to code this if I have to?? I guess a quicksort would do the trick, is there more efficient sorting algos?? (those arrays tends to get huge)

  Thanks

skip
0
Comment
Question by:skipbo
7 Comments
 
LVL 14

Accepted Solution

by:
SBennett earned 100 total points
ID: 6345916
Some one else may be able to come up with a more efficient way but this will work.

---------------------------------------------------------

<!--- here I build a 2D array, but you can probaly skip this step because you already have one --->
<cfset MyArray = ArrayNew(2)>

<cfset MyArray[1][1] = "ccc">
<cfset MyArray[1][2] = "this triple c">

<cfset MyArray[2][1] = "bbb">
<cfset MyArray[2][2] = "this triple b">

<cfset MyArray[3][1] = "aaa">
<cfset MyArray[3][2] = "this triple a">


<!--- Create a temporary array of the values of the dimension from the first array that you want to sort and sort them --->
<cfset temparray = arraynew(1)>
<cfloop from="1" to="#arraylen(MyArray)#" index="i">
     <cfset temparray[i] = MyArray[i][1]>
</cfloop>
<cfset arraysort(temparray, "textnocase", "asc")>


<!--- Create a new array and poplulate it with the data from
     the first array using the order of the temp array --->
<cfset sortedarray = arraynew(2)>

<cfloop from="1" to="#arraylen(temparray)#" index="i">
     <cfloop from="1" to="#arraylen(MyArray)#" index="i2">
          <cfif temparray[i] eq MyArray[i2][1]>
               <cfset sortedarray[i][1] = MyArray[i2][1]>
               <cfset sortedarray[i][2] = MyArray[i2][2]>
               <cfbreak>
          </cfif>
     </cfloop>
</cfloop>

-----------------------------------------------------------
0
 
LVL 19

Expert Comment

by:cheekycj
ID: 6346483
here is a bubble sort implementation from a web site that I use in my code (its in asp but converting it to cf should be trivial):
Sub DualSorter( byRef arrArray, DimensionToSort )
    Dim row, j, StartingKeyValue, StartingOtherValue, _
        NewStartingKey, NewStartingOther, _
        swap_pos, OtherDimension
    Const column = 1
   
    ' Ensure that the user has picked a valid DimensionToSort
    If DimensionToSort = 1 then
          OtherDimension = 0
     ElseIf DimensionToSort = 0 then
          OtherDimension = 1
     Else
         'Shoot, invalid value of DimensionToSort
         Response.Write "Invalid dimension for DimensionToSort: " & _
                        "must be value of 1 or 0."
         Response.End
     End If
   
    For row = 0 To UBound( arrArray, column ) - 1
    'Start outer loop.
   
        'Take a snapshot of the first element
        'in the array because if there is a
        'smaller value elsewhere in the array
        'we'll need to do a swap.
        StartingKeyValue = arrArray ( row, DimensionToSort )
        StartingOtherValue = arrArray ( row, OtherDimension )
       
        ' Default the Starting values to the First Record
        NewStartingKey = arrArray ( row, DimensionToSort )
        NewStartingOther = arrArray ( row, OtherDimension )
       
        swap_pos = row
         
        For j = row + 1 to UBound( arrArray, column )
        'Start inner loop.
            If arrArray ( j, DimensionToSort ) < NewStartingKey Then
            'This is now the lowest number -
            'remember it's position.
                swap_pos = j
                NewStartingKey = arrArray ( j, DimensionToSort )
                NewStartingOther = arrArray ( j, OtherDimension )
            End If
        Next
         
        If swap_pos <> row Then
        'If we get here then we are about to do a swap
        'within the array.
            arrArray ( swap_pos, DimensionToSort ) = StartingKeyValue
            arrArray ( swap_pos, OtherDimension ) = StartingOtherValue
           
            arrArray ( row, DimensionToSort ) = NewStartingKey
            arrArray ( row, OtherDimension ) = NewStartingOther
           
        End If    
    Next
End Sub



if you need help converting it let me know.

CJ
0
 

Author Comment

by:skipbo
ID: 6346531
Hi,

  SBennett, I tried your solution, it works really well with small arrays, but when things get bigger, it's really taxing on the server resources.

  I'll check if I could mix in cheekycj idea and see what happens.

  I wonder if the quicksort can be implemented in cold fusion. It use some recursion, but what do you guys think??

  Thanks a lot guys. I'll let you know what happens...

skip
0
Backup Your Microsoft Windows Server®

Backup all your Microsoft Windows Server – on-premises, in remote locations, in private and hybrid clouds. Your entire Windows Server will be backed up in one easy step with patented, block-level disk imaging. We achieve RTOs (recovery time objectives) as low as 15 seconds.

 
LVL 14

Expert Comment

by:SBennett
ID: 6346625
Yes, I can see how my suggestion would take a lot of proccessing time if the array is extremely large.

I've never really done that before so that was the first solution I thought of. If you come up with a faster solution pleas post it so I can refer to it later.
-scott

0
 

Author Comment

by:skipbo
ID: 6349676
Hello guys,

  I spent some time looking around and found this  answer from CF_SPIKE. It implements the quick sort algo. So thanks to him and here it is:

------------------------------------------------------
Answer provided by : CF_SPIKE
------------------------------------------------------

Calling Page:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">

<html>
<head>
    <title>Quick Sort</title>
</head>

<body>
<!--- 2 Dimensional array sorting. Second Array dimension represents:
1 - Employee No
2 - Name
3 - Age
4 - Sex
5 - Date of Birth
6 - Department --->

<CFSCRIPT>
 myArray = ArrayNew(2);
 myArray[1][1] = '1';
 myArray[1][2] = 'Spike';
 myArray[1][3] = '28';
 myArray[1][4] = 'Male';
 myArray[1][5] = 'CreateDate(1972,08,10)';
 myArray[1][6] = 'Training';
 
 myArray[2][1] = '2';
 myArray[2][2] = 'Jon';
 myArray[2][3] = '26';
 myArray[2][4] = 'Male';
 myArray[2][5] = 'CreateDate(1974,10,23)';
 myArray[2][6] = 'Consulting';
 
 myArray[3][1] = '2';
 myArray[3][2] = 'Bob';
 myArray[3][3] = '22';
 myArray[3][4] = 'Male';
 myArray[3][5] = 'CreateDate(1979,03,23)';
 myArray[3][6] = 'Sales';
 
 myArray[4][1] = '2';
 myArray[4][2] = 'Jane';
 myArray[4][3] = '20';
 myArray[4][4] = 'Female';
 myArray[4][5] = 'CreateDate(1980,11,29)';
 myArray[4][6] = 'Sales';
 
</CFSCRIPT>

<CF_QuickSort  
   Array="#MyArray#"
   r_Array="SortedArray"
   SortType="Numeric"
   SortItem="1">


</body>
</html>


custom Tag:

<CFPARAM NAME="Attributes.Array">
<CFPARAM NAME="Attributes.r_Array">

<!--- SortItem is the index in the second dimension
of the array which we want to sort by --->
<CFPARAM NAME="Attributes.SortItem">

<!--- SortType can be Numeric, Text, TextNoCase --->
<CFPARAM NAME="Attributes.SortType">

<!--- SortOrder can be Desc, Asc --->
<CFPARAM NAME="Attributes.SortOrder" DEFAULT="Asc">

<!--- Initialize a list to hold the array elements --->
<CFSET NameList = "">

<!--- Loop over the Array creating a list of the
elements by which we want to sort  --->
<CFLOOP From="1" To="#ArrayLen(Attributes.Array)#" index="i">

 <CFSET NameList = ListAppend(NameList,Attributes.Array[i][Attributes.SortItem])>

</CFLOOP>

<!--- Create a new sorted list. Sorting by the
parameters delcared above --->
<CFSET NewList = ListSort(NameList,Attributes.SortType,Attributes.SortOrder)>

<!--- Create a New array sorted according to our requirements --->
<CFSET NewArray = ArrayNew(2)>
<CFSET Counter = 1>
<CFLOOP LIST="#newList#" INDEX="i">
<CFSET NewArray[counter] = Attributes.Array[ListFind(NameList,i)]>
<CFSET Counter = Counter + 1>
</CFLOOP>

<CFSET "Caller.#Attributes.r_Array#" = NewArray>
0
 

Expert Comment

by:EGray
ID: 7529640
The CF_SPIKE solution and its variants won't work properly if the data in the array contains duplicate values in the sorted column. I came to this site looking for an answer to the original question in this thread, and tried this solution. But I couldn't use it because I do have duplicate values.

I came up with two different ways of doing this, both of which work no matter what the values are. The first is to loop through the array, combine the rows using a separator - I used CHR(30) - into a single dimension array, sort it using arraysort(), and then set up a new array and loop through your sorted array, populating the new array by pulling each element apart again using GetToken().

However, I still had a little problem to overcome. The column which I want to sort contains numeric (integer) values. But now with the combined data, a numeric sort fails because the data is no longer a number, and a text sort returns incorrect order (1,10,2, etc.). The solution: use the NumberFormat operator to pad zeros in front of the number, do a text sort, and then use NumberFormat again to drop the zeros in the final array.

Sample code, for a 2D array with 3 columns:

<CFSET MyDelim = Chr(30)>
<CFSET My1DArray = ArrayNew(1)>
<CFLOOP INDEX="LoopCount" FROM = "1" TO = "#ArrayLen(MyOld2DArray)#">
     <CFSET My1DArray[LoopCount]= "#NumberFormat(MyOld2DArray[LoopCount][1],0000000.)##MyDelim##MyOld2DArray[LoopCount][2]##MyDelim##MyOld2DArray[LoopCount][3]#">
 </CFLOOP>
 
<CFSET temp = ArraySort(My1DArray, "TextNoCase", "Desc")>

<CFSET My2DArray = ArrayNew(2)>
<CFLOOP INDEX="LoopCount" FROM = "1" TO = "#ArrayLen(My1DArray)#">
     <CFSET My2DArray[LoopCount][1] = NumberFormat(GetToken(My1DArray[LoopCount],"1", "#MyDelim#"))>
      <CFSET My2DArray[LoopCount][2] = GetToken(My1DArray[LoopCount],"2", "#MyDelim#")>
      <CFSET My2DArray[LoopCount][3] = GetToken(My1DArray[LoopCount],"3", "#MyDelim#")>
 </CFLOOP>

But this is pretty clunky. The more elegant solution, if you have access to a SQL database, is to create a dedicated table to do the sorting. Delete all rows in the table, insert your array, then query the table using "ORDER BY" and then empty the table again when you are done.


0
 
LVL 4

Expert Comment

by:hanneman
ID: 9434847
well, it wasnt trivial, but here is the bubble sort for CF. phew. please post any improvements.

<cfset tmparr = ArrayNew(2)>
 <cfset tmparr[1][1] = 1>
 <cfset tmparr[1][2] = "reca">
 <cfset tmparr[2][1] = 4>
 <cfset tmparr[2][2] = "recb">
 <cfset tmparr[3][1] = 2>
 <cfset tmparr[3][2] = "recc">
 <cfset tmparr[4][1] = 5>
 <cfset tmparr[4][2] = "recd">
 
<cfscript>
 Function DualSorter(arrArray, DimensionToSort)
 {
    var row = 0;
      var j = 0;
      var StartingKeyValue = "";
      var StartingOtherValue = "";
      var NewStartingKey = "";
      var NewStartingOther = "";
      var swap_pos = "";
      var OtherDimension = "";
      var column = 1;
          
    // Ensure that the user has picked a valid DimensionToSort
    If (DimensionToSort eq 1){
            OtherDimension = 0;}
      
      If (DimensionToSort eq 0){
            OtherDimension = 1;}
      
      If (Otherdimension eq "") {
          //Shoot, invalid value of DimensionToSort
          Writeoutput("Invalid dimension for DimensionToSort: must be value of 1 or 0.");
       break;
       }
      
       dimensiontosort = incrementvalue(dimensiontosort);
       otherdimension = incrementvalue(otherdimension);
   
    For (row = 1; row lte arraylen(arrarray);row=row+1){
    //Start outer loop.
   
        //Take a snapshot of the first element
        //in the array because if there is a
        //smaller value elsewhere in the array
        //we'll need to do a swap.
            StartingKeyValue = arrArray[row][DimensionToSort];
        StartingOtherValue = arrArray[row][OtherDimension];
       
        // Default the Starting values to the First Record
        NewStartingKey = arrArray[row][DimensionToSort];
        NewStartingOther = arrArray[row][OtherDimension];
       
        swap_pos = row;
            
        For (j = row + 1; j lte arraylen(arrarray);j=j+1){
        //Start inner loop.
            If (arrArray[j][DimensionToSort] gt NewStartingKey)
                  {
            //This is now the lowest number -
            //remember it's position.
                swap_pos = j;
                NewStartingKey = arrArray[j][DimensionToSort];
                NewStartingOther = arrArray[j][OtherDimension];
            }
        }
            
        If (swap_pos neq row) {
        //If we get here then we are about to do a swap
        //within the array.
            arrArray [swap_pos][DimensionToSort] = StartingKeyValue;
            arrArray [swap_pos][OtherDimension] = StartingOtherValue;
           
            arrArray [row][DimensionToSort] = NewStartingKey;
            arrArray [row][OtherDimension] = NewStartingOther;
          }      
    }
      return arrarray;
}

writeoutput(arraylen(tmparr)&"<br>");
tmparr = dualsorter(tmparr, 0);

for (n = 1; n lte arraylen(tmparr);n=n+1)
{
writeoutput(#tmparr[n][1]#&","&#tmparr[n][2]#&"<br>");
}

</cfscript>
0

Featured Post

Why You Should Analyze Threat Actor TTPs

After years of analyzing threat actor behavior, it’s become clear that at any given time there are specific tactics, techniques, and procedures (TTPs) that are particularly prevalent. By analyzing and understanding these TTPs, you can dramatically enhance your security program.

Join & Write a Comment

If you don't have the right permissions set for your WordPress location in IIS, you won't be able to perform automatic updates. Here's how to fix the problem.
Meet the world's only “Transparent Cloud™” from Superb Internet Corporation. Now, you can experience firsthand a cloud platform that consistently outperforms Amazon Web Services (AWS), IBM’s Softlayer, and Microsoft’s Azure when it comes to CPU and …
Sending a Secure fax is easy with eFax Corporate (http://www.enterprise.efax.com). First, Just open a new email message.  In the To field, type your recipient's fax number @efaxsend.com. You can even send a secure international fax — just include t…
Polish reports in Access so they look terrific. Take yourself to another level. Equations, Back Color, Alternate Back Color. Write easy VBA Code. Tighten space to use less pages. Launch report from a menu, considering criteria only when it is filled…

705 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

12 Experts available now in Live!

Get 1:1 Help Now