javascriptsorting

Different sorting


I have two (2) arrays:

var stringArray = [Tom, Michael, Bob, Thomas];
var numberArray = [2, 3, 1, 4]

I need to sort stringArray for:

[Bob, Tom, Michael, Thomas]

How I can achieve this?

ect.

Bob = 1 in number array
Tom = 2 in number arra
Michael = 3 ....

Solution

  • numberArray[] is a rank (+1). This example creates another array I[], converting the rank+1 into sorted indices (0 to n-1), then reorders stringArray[] and I[] in place in O(n) time (each store places a value in it's final sorted position). C example, which should be convertible to javascript:

    char * stringArray[] = {"Tom", "Michael", "Bob", "Thomas"};
    int numberArray[] = {2, 3, 1, 4};
    int I[4];                       // change 4 to array size
    int i, j, k;
    char * tS;                      // temp for stringArray element
        // convert rank+1 to sorted index I[]
        for(i = 0; i < 4; i++)      // change 4 to array size
            I[numberArray[i]-1] = i;
        // reorder stringArray in place
        for(i = 0; i < 4; i++){     // change 4 to array size
            if(i != I[i]){
                tS = stringArray[i];
                k = i;
                while(i != (j = I[k])){
                    stringArray[k] = stringArray[j];
                    I[k] = k;
                    k = j;
                }
                stringArray[k] = tS;
                I[k] = k;
            }
        }