Sorting array with VBS

I am reading data from file to array with For Next loop. I get the data to array but when I try to pass this unsorted array to bubblesort function I get type mismatch error. I don't understand why.
'This causes type mismatch
arrTestArray = BubbleSort(arrTestArray)
Function BubbleSort(arrValues)
    Dim j, k, Temp
    For j = 0 To UBound(arrValues) - 1
        For k = j + 1 To UBound(arrValues)
            If (arrValues(j) > arrValues(k)) Then
                Temp = arrValues(j)
                arrValues(j) = arrValues(k)
                arrValues(k) = Temp
            End If
        Next
    Next
 BubbleSort = arrValues
End Function

I should also note that in Office VBA and in VB6 we can do this:
Dim someArray(1 To 10)Dim someArray(-3 To 12)
Dim someArray(-10 To -1)This is where the need for LBound comes from. If you generate an array like this in Office and pass it to VBScript then you need to use LBound.
The misuse of UBound -1 is a takeoff on using Length for the limit.
for I = 0 to A.Length -1
which would be better stated like this:
i=0
while(i < a.length)
   i = i - 1
wend
Of course VBScript doesn't not have an array length function.
¯\_(ツ)_/¯

Similar Messages

  • Sort array with equal elements

    Hi, I'm a new one.
    I have a problem to sort 2d array with equal elements (it has 5000000 of elements from 1-255) for example:
    1 2 1 1 3 4 5 5 6 1 2 3 (value from 1-255)
    2 2 1 1 3 3 3 3 4 4 4 1 (value from 1-255)
    And I need make array or matrix 255 rows vs 255 colomns, and count how many equal elements for example:
      1  2 3 4 5 6
    1 0 1 0 1 0 0
    2 0 1 0 1 0 0
    3 1 0 1 0 0 0 
    4 0 0 1 0 0 0
    5 0 0 2 0 0 0
    6 0 0 0 1 0 0
    I'll be happy if someone could help me

    I understand that it's very complicated explain.
    I build 2d array from two 1darray each of them has values 1-255. So right now i must constract array or matrix 255x255 where must calculat how many times value from (1-255) for one array in another array and write this sum for each value 1-255. I try to show it
    1 2                         so I need array 3x3; for first row for value 1 I have two times value 3 and one time value 2
    2 2                                                                                    2 I have two times value 1 and one time value 2 and one time value 3
    3 2                                                                                    3 I have two times value 2 and one time value 3 
    3 2              so my result matrix will be      1   2  3
    3 3                                                       1  0  1  2
    2 3                                                       2  2  1  1
    2 1                                                       3  0  2  3
    2 1
    1 3
    1 3
    Maybe its more clear

  • Sort an array with two fields

    i have an array with three fields: id, name and date.
    i want to sort it by name first and then date.
    the size of my array could be as large as 1 million.
    what could be the most efficient way to do so?
    tia!

    It's very inefficient to sort an array on "the fly".
    In that case at least use a linked list so you don't
    have to move all elements after the insertion point to
    make room for a new insert. But it's much better to
    sort afterwards when all elements are in the array.Use a TreeSet. A linked list will be slower than a TreeSet, I suspect.
    I believe that with a TreeSet, insertions will be somewhat slower (O(logN) vs O(c)), but the subsequent sorting of a linked list will be, what, at least O(NlogN) and possibly O(N^2)? And when you're inserting the first elements into the TreeSet, it should be closer to O(c) anyway, whereas the after-the-fact sorting of a LinkedList wouldn't have an advantage like that.
    Then if necessary extract an array out of the TreeSet when you're done creating/inserting elements.
    But really, use a database.

  • Populate block with an sorted array contents.

    hey,
    i'm trying to populate a block (forms 10 vs. db 10g) with data from an array.
    the data should be sorted.
    what is the easiest way to do it?
    another deatails (array structure)) will supplied if nessecary.
    thanks , yair

    How do you populate your array? If you populate it with a query in some way the easiest way would be not to use an array at all and simply populate the block with your query. This would spare you manually populating the block and implementing a sort algorithm yourself (just use order by)
    If the data comes from what ever else source a pipelined function comes to my mind which would enable you to query your array with SQL and letting the SQL Engine do the sort. You'd just have to use a from-clause query on your block
    http://docs.oracle.com/cd/B19306_01/appdev.102/b14289/dcitblfns.htm
    cheers

  • Best algorithm to sort semi-sorted arrays?

    I am trying my hand at the hutter prize (http://prize.hutter1.net/)
    My current compression algorithm sorts an array of Comparable Objects every main cycle.
    -This array of objects can potentically increase by one object per cycle.
    -Each object's comparision value can change per cycle, however its order is mostly kept.
    This means that the over all order of the objects are similar between cycles.
    Is there an sorting algorithm which can take advantage of the semi-sorted state of the array?
    I was using the default Arrays.sort() however it does not seem to make much use of the semi-sorted input array and is too slow for my use.
    In order to speed up the sorting i have relaxed the need to be in strict order. I.e there can be some objects out of order.
    To this end I have developed a BucketSort which i thought should speed up the sorting however it seems to have the opposite effect!
    Is there any reason why this implementation is quite slow? (three times as slow as Array.sort() )
       private static int MAX_BUCKET=65535;
       private static Word[] buckets=new Word[MAX_BUCKET];
       public static void bucketSortReverse (Word[] a, int n)
            int i;
            int count=1;
            int index;
            Word curr;
            // fill up the buckets with the input words
            for (i=0;i<n;i++)
                 curr=a;
              index=(int) (curr.probablility*MAX_BUCKET);
              curr.next=buckets[index];
              buckets[index]=curr;
         // iterate over the buckets and construct the sorted words
         for (i=0;i<MAX_BUCKET;i++)
              curr=buckets[i];
              if (curr!=null)
                   while (curr!=null)
                        a[n-count++]=curr;
                        curr=curr.next;
                   buckets[i]=null;
    NOTE Currently my input Word array contains a maximum of 6000 words.
    Lowering the number of bins reduces the accuraccy of the sort and does not provide much increase in speed :(
    I have found some Open Source code which by default performs very similarly to Arrays.sort in terms of speed and have modified it to be non-strict in its ordering.
    This modified sorting algothim is approximately 15% faster but is still really not fast enough.
    By reducing the strict ordering of the sorting algorithm i have also reduced the level of compression. Ultimately i would like to have a fast sorting algothrim which takes into acount semi-sorted objects with out reducing strictness of the sort.
    Any ideas?

    Tree removal takes O(logn) and insertion takes O(logn). Compare this to an array where potentially a large number of elements need to be shifted O(n).
    Usually it takes hundreds of thousands of elements to notice a difference. So if your data is relatively small, then it may not be worth trying to optimize it.
    test of the parent may need to be performed to determine The balanced binary tree (TreeSet) that comes with the JDK doesn't allow access to the internal structure of the tree, so testing the parent isn't available. Even if it was, it would still take an O(logn) lookup to find the node and get its parent, so it wouldn't be a significant improvement.

  • Removes duplicates from a sorted array without having to create a new array

    Funcation removes duplicates from a sorted array without having to create a new array

    Funcation removes duplicates from a sorted array
    without having to create a new arrayIs a 'funcation' like a vacation but more fun or
    something?LMFAO. You just jumped with both feet on one of my biggest peeves. I've been outed!
    Actual words/phrases I've seen used which I hate with every fiber of my being:
    "Mrs. Freshly's"
    "McFlurry"
    "Freshissimo"
    "Spee-dee"
    "Moons Over My Hammy"
    One of my favorite SNL skits had Will Ferrell leading a panel of movie reviewers (they're the worst for this kind of junk). Each one had some cheesy pun to describe their respective movie. Ferrell topped the show off with his endorsement of "Fantasia 2000 is Fantasgreat!"
    LOL.
    "Come to Slippy Village - it's a FUNCATION!"
    &#167; (runs off, laughing maniacally, head explodes)

  • Exception handling in sorting arrays

    Hi all, I have a problem with the use of the built in java sort fo arrays. My program works on an array with 4 or 5 entities. When I run it in some folders it works but not in others. I get the following error after compilation, where "ResultData" is the class of array to be sorted:Exception in thread "main" java.lang.NullPointerException
    at ResultData.compareTo(TextEdit.java:1215)
    at java.util.Arrays.mergeSort(Arrays.java:1064)
    at java.util.Arrays.mergeSort(Arrays.java:1071)
    at java.util.Arrays.mergeSort(Arrays.java:1072)
    at java.util.Arrays.mergeSort(Arrays.java:1071)
    at java.util.Arrays.mergeSort(Arrays.java:1071)
    at java.util.Arrays.mergeSort(Arrays.java:1071)
    at java.util.Arrays.sort(Arrays.java:1014)
    at java.util.Collections.sort(Collections.java:78)
    [\code]Can any one give a suggestion?                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   

    Here is the code for the class "ResultData"class ResultData implements Comparable
         String file1;
         String file2;
         double var, var1, var2;
         public ResultData(String f1,String f2,double v, double x, double y)
                   file1= f1; file2=f2;
                   var=v; var1=x; var2=y;
         public String getFile1Name()
              return file1;
         public String getFile2Name()
              return file2;
         public double getVar()
              return var;
         public double getVar1()
              return var1;
         public double getVar2()
              return var2;
         public String toString()
              return file1+"          "+file2+"          "+var+"          "+var1+"          "+var2;
           public int compareTo(Object o)
              ResultData r= (ResultData)o;
              double result = this.getVar()- r.getVar();
              if (result < 0.0)         return -1;
              else if(result > 0.0)     return 1;
              else return 0;
    } // ends class ResultData

  • TreeSet vs Collection.Sort / Array.sort for Strings

    Gurus
    I am pondering weather to use TreeSet vs the Collections.sort / Array.sort for sorting Strings.
    Basically I have a list of Strings, i need to perform the following operations on these Strings
    1) Able to list Strings starting with a Prefix
    2) Able to list Strings Lexically greater than a String
    Any help would be greatly appreciated!
    Thanks a bunch

    SpaceShuttle wrote:
    Gurus
    I am pondering weather to use TreeSet vs the Collections.sort / Array.sort for sorting Strings.
    Basically I have a list of Strings, i need to perform the following operations on these Strings
    1) Able to list Strings starting with a Prefix
    2) Able to list Strings Lexically greater than a String
    Any help would be greatly appreciated!
    Thanks a bunchBig-O wise, there's no difference between sorting a list of N elements or inserting them one by one in a tree-set. Both take O(n*log(n)). But both collections are not well suited for looking up string that start with a certain substring. In that case you had better use a Patricia tree (or Radix tree).
    Good luck.

  • Sort array method...

    Hi all,
    I have a float array of many rows and two columns.
    I was wondering whether it is possible to sort this array with calls of java api, just be specifing the column index number.
    Thank you.

    That works with Arrays.sort and Comparator
    import java.util.*;
    class FloatArray {
    public static void main(String[] args){
    Random rand=new Random();
    float[][] floatArray=new float[10][2];
    // filling the array with random numbers
    for(int i=0; i<10; i++)
        for(int j=0; j<2; j++) {
            floatArray[i][j]=rand.nextFloat();
    // sorting the first column
    Arrays.sort(floatArray, new Comparator<float[]>() {
        public int compare(float[] f1, float[] f2)  {
            if (f1[0]>f2[0]) return 1;
            else if (f1[0]==f2[0]) return 0;
            else return -1;
    for(int i=0; i<10; i++) {
        for(int j=0; j<2; j++) {
            System.out.print(floatArray[i][j]+", ");
        System.out.println();
    System.out.println();
    System.out.println();
    // sorting the second column
    Arrays.sort(floatArray, new Comparator<float[]>() {
        public int compare(float[] f1, float[] f2)  {
            if (f1[1]>f2[1]) return 1;
            else if (f1[1]==f2[1]) return 0;
            else return -1;
    for(int i=0; i<10; i++) {
        for(int j=0; j<2; j++) {
            System.out.print(floatArray[i][j]+", ");
        System.out.println();
    }

  • How do I cerate an array with a set of numbers lets say 1 through 12 random order but no repeating.

    How do I cerate  an
    array with a set of numbers lets say 1 through 12 random order but no
    repeating.
    I know this should be easy but my brain wont work
    right now
    Solved!
    Go to Solution.

    OK, here's the handmade version.
    It is useful to know that arrays of clusters are sorted by the cluster order of the elements. Simply bundle random numbers with numbers 1-12 in a loop, create an array at the output tunnel, sort the array by the random number, and extract the number array. It will be shuffled.
    Message Edited by altenbach on 06-04-2007 09:20 PM
    LabVIEW Champion . Do more with less code and in less time .
    Attachments:
    shuffleArray.png ‏5 KB

  • Sun C++ std::sort coredump during sorting array of long values

    Hello,
    I got core dump during execution following test program on both Solaris 9 (compile by CC: Sun C++ 5.5 Patch 113817-19 2006/10/13) and Solaris 10 platforms (compile by CC: Sun C++ 5.9 SunOS_sparc Patch 124863-01 2007/07/25).
    Core is dumped during sorting array of about 120k elements of unsigned long types using STL std:sort. The input data is available at link: [file.txt|http://www.savefile.com/files/1924004]
    When I change sorting methods to std::stable_sort program works fine.
    The funny thing is that when I change order of last two values of input data (swap), sorting is successful with std::sort.
    Can anyone tell me if it is Sun C++ compiler bug ?Can I use std::stable_sort method safely?
    Below code:
    #include <iostream.h>
    #include <fstream.h>
    #include <set>
    #include <string>
    int main( int argc, char** argv )
      char readStr[256];
      ifstream file;
      unsigned long *l;
      int i=0;
      l = new unsigned long[119016];
      if (l ==0)
        cout << "Error in allocate memory";
        return -1;
      file.open("file.txt");
      if (!file)
        cout << "Error in openening file";
        return -1;
      while(file.getline(readStr, 256,'\n'))
        cout << readStr<<endl;
        l= atol(readStr);
    cout << l[i]<<endl;
    i++;
    std::sort(l,l+119016); //core dump here!!!
    for (i=0;i<119016;i++)
    cout <<l[i]<<endl;
    file.close();
    delete [] l;
    return( 0 );
    Greetings
    Robert                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   

    You have run into bug 6588033 "std::sort from libCstd loops", which is fixed in current patches.
    Get the current patches for Sun Studio and also the current patch for the C++ runtime libraries (SUNWlibC patch).
    You can find them here:
    [http://developers.sun.com/sunstudio/downloads/patches/index.jsp]
    Sun C++ 5.5 probably does not have the fix, since it is quite old and falling out of support.
    C++ 5.9 does have the fix.

  • I need sorting VI that returns the sorted array element's positions in the unsorted array

    I need a VI that will very quickly (n log n) sort a 1D array of doubles.  This VI should not only output the sorted array, but for each of the sorted array elements, it should also output that sorted array element's position in the unsorted array.  So for example if the input array were:
    unsorted_array
    4.1
    2.3
    7.0
    5.6
    10.2
    Then the output arrays would be:
    sorted_array
    2.3
    4.1
    5.6
    7.0
    10.2
    indices_array
    1 (the value 2.3 is located at position 1 in the unsorted_array)
    0 (the value 4.1 is located at position 0 in the unsorted_array)
    3 (the value 5.6 is located at position 3 in the unsorted_array)
    2 (the value 7.0 is located at position 2 in the unsorted_array)
    4 (the value 10.2 is located at position 4 in the unsorted_array)
    This way I could generate the sorted_array using just the indices_array and the unsorted_array.  Has anyone written a nifty piece of code to do this?  I did some research on (n log n) sorting algorithms but most of them use recursion which I don't know how to do in LabVIEW.  It would also be nice to have an algorithm like this that could sort an array of strings.
    cheers,
    Richard

    Try something like the attached example (LabVIEW 7.0). I think it does what you need.
    (To understand the code, it is important to know that arrays of clusters are sorted by the first element in the cluster).
    Sort array itself sorts also array of strings, so you could just substitute, keeping the rest of the code the same.
    Sort array uses a variation of quicksort, so it should have about NlogN complexity.
    (If you think you only need the array of indices to later generate the sorted array, it does not make much sense to even do it. To get the indices, you need to sort the array anyway. You should just sort the plain array directly.
    Message Edited by altenbach on 07-13-2005 03:47 PM
    LabVIEW Champion . Do more with less code and in less time .
    Attachments:
    SortAndIndex.vi ‏26 KB

  • Sorting array

    I know how to sort the array of strings alpha numerically but my problem is that the numerical values will not follow there corresponding strings
    here is the code i am using:
    Harold Timmis
    [email protected]
    Orlando,Fl
    *Kudos always welcome
    Solved!
    Go to Solution.
    Attachments:
    testingfileIO.vi ‏35 KB

    Hi.
    It's nice to have "sorting array" icon.
    But I have problem with programming similar option. I want to sort my sine samples taken in more periods to just one period.
    Beside defining that mycurrent sample should be less than next one, and greater from previous one in one case, I should take in consider that derivation could be positive or negative. While negative derivation, next sample should be less then current and so one.
    Can someone help me with programming?
    I've extracted the first period, and then I have to go trough each sample and compare him. When logic is well,I get the index and putinsert elemt in array.
    I think that I'm having problem with while loops. I don't know where to put them.
    I'm attaching VI. beacuse I'm working on Labview 9.0, I'm attaching also a pic.
    Thanks in advance.
    Attachments:
    resampling.vi ‏89 KB
    Untitled.jpg ‏135 KB

  • Sorting array vs sorting paginated array

    ...pulling in a long list of photos in a gallery, and I have
    a sort function working within the pages of data fine. I need to
    bring it back out of the paging stuff so that it sorts the data,
    THEN passes to the paging function.
    My data comes from mysql > php > xml > Flex into an
    ArrayCollection, referred to in MXML as {acSlides}.
    Pass the array collection to the paging system like:
    <utils:FXCPager id="fxcPager" pageIndex="{currentPage}"
    pageSize="{pageSize}" dataProvider="{acSlides}" />
    then assign in repeater:
    <mx:Repeater id="slideRepeater"
    dataProvider="{fxcPager.pageData}">...</>
    There is a button for sorting that calls a function a la:
    private function sortByRating():void {
    var sort:Sort = new Sort();
    sort.fields = [new SortField("rating",false,true)];
    fxcPager.pageData.sort = sort;
    toggleRating = false;
    fxcPager.pageData.refresh();
    What do I need to do to get this sort function to work on the
    {acSlides} array collection instead of {fxcPager.pageData} ???
    Thanks!

    OK I have resolved the error by importing the class adGroup. However now I am back to the original problem which is how to sort the DisplayName alphabetically and keep the associated link in tact. I created the class to avoid sorting parellel arrays but I am afraid it solved nothing as I have no idea how to sort the class. I tried just sorting it like an array:
      Arrays.sort(bAD.getGroups()but receive the following error:
    java.lang.ClassCastException: com.mylbean.adGroup incompatible with java.lang.Comparable
    at java.util.Arrays.mergeSort(Arrays.java:1160)
    at java.util.Arrays.sort(Arrays.java:1131)
    >
    I would assume this message is caused because I cannot sort a class array using this method. But being newer to Java I really have no idea how to get the class to sort by DisplayName before displaying to the user.
    So at this point the code works fine but how do I display alphabetically? All suggestions are appreciated.

  • Getting arrays with same types

    Hi,
    I'm writing an application and at a certain point I need to be able to compare constraints of the same type to see if there are any conflicts.
    At first you get an array with all kinds of constraints in it, not sorted and not knowing wich types are in there. I wrote a comparator to sort the array, which works. After sorting I count the different types there are. Now I would like to make a vector for each type and fill these vectors with the constraints, but I'm not sure how I can do this.
    What I have so far is:
    //first the array of preferred constraints is being examined,
    //if there are conflicts: arbitrarily one of both
    //preferred constraints is being eliminated
    Arrays.sort(pref,new ConstraintTypeComparator());
    //conflicts are only possible between constraints of the same
    //type so after sorting, we get vectors of simillar constrainttypes
    for(int i = 0; i < pref.length; i++){
       //count how many different types there are in the array
       int countTypes = 1;
       for (int j = 0; j < pref.length - 1; j++){
        if(! pref[j].getConstraintType().equals(
            pref[j+1].getConstraintType ())) countTypes++;}
    //make vectors with only constraints of the same type in them
    //for each type there is
        for (int k = 0; k < countTypes; k++){                 
            //not sure how to do this
    [\code]
    Is there an easy way/method I can use to create (and fill) these vectors?
    thanks

    Very funny, but doesn't help one bit...
    You don't know in advance how many types there will be, so in your code indeed if you have more than three: panic(); not only you don't know how many types there will; you also don't know which types there will be. The type of a constraint is a string though, so you could get, save and compare them...
    Isn't there a way to do something like:
    for (int i = 0; i < length; i++){
      Vector type+i+ = new Vector;
    //blalba
    [\code]

Maybe you are looking for

  • Best Buy Willowbrook Store 214

    I purchased a 13" Macbook Pro from this store on January 26, 2013. The explained to the best buy employee that I wanted the 2 year warranty with the accidental damage protection, as this is the plan we get with all of our laptops. He agreed and I che

  • Error while accessing ESS Loan Request.

    Hi Experts, While accessing ESS Loan request for Country grouping 40 India am getting below mentioned error saying that 500 Internal Server Error. I have maintained the settings for Leave request and maintained Infotype 45 Loans for employee. But it

  • How to calculate Total Shipping Volume in Sales Order ?

    Hello, Please give me suggestion for calculating Total Shipping Volume or Total Shipping Quantity in Sales Order. And suggest if there is any existing report available to get "Total Shipping Volume". Thank You. Regards, Meghana

  • Retrieve fieldtext with dynamic table.

    Hy everyone , Is it possible to retrieve the long or medium text of a field label in data element using cl_abap_elemdescr or cl_abap_typedescr ? Thank's a lot. !!

  • Verify that MBR hasn't been modified since last boot / overwrite it

    I need a way to check if the MBR and /boot partition have been modified BEFORE the system boots and if so, a way to overwrite them with "trusted" backups, again BEFORE the system boots. Is it possible to accomplish this by booting SOME SYSTEM (which