Thread: Sort array and save the new order of elements

Hybrid View

Previous Post Previous Post   Next Post Next Post
  1. #1
    Registered User
    Join Date
    Apr 2013
    Posts
    1,658
    It would be simpler to sort array_order, using a[array_order[...]] for the compares and pivot points. Then afterwards, you can reorder or copy a according to array_order. The copy is simple, using i to index through the array, b[i] = a[array_order[i]]; . The in place reorder involves a variation of cycle sort (vA is the array, vI is the array of sorted indices):

    Code:
    void reorder(vector<int>& vA, vector<size_t>& vI)  
    {
    size_t i, j, k;
    int t;
        for(i = 0; i < vA.size(); i++){
            if(i != vI[i]){
                t = vA[i];
                k = i;
                while(i != (j = vI[k])){
                // every move places a value in it's final location
                    vA[k] = vA[j];
                    vI[k] = k;
                    k = j;
                }
                vA[k] = t;
                vI[k] = k;
            }
        }
    }

  2. #2
    Registered User
    Join Date
    May 2014
    Posts
    69
    Quote Originally Posted by rcgldr View Post
    It would be simpler to sort array_order, using a[array_order[...]] for the compares and pivot points. Then afterwards, you can reorder or copy a according to array_order. The copy is simple, using i to index through the array, b[i] = a[array_order[i]]; . The in place reorder involves a variation of cycle sort (vA is the array, vI is the array of sorted indices):

    Code:
    void reorder(vector<int>& vA, vector<size_t>& vI)  
    {
    size_t i, j, k;
    int t;
        for(i = 0; i < vA.size(); i++){
            if(i != vI[i]){
                t = vA[i];
                k = i;
                while(i != (j = vI[k])){
                // every move places a value in it's final location
                    vA[k] = vA[j];
                    vI[k] = k;
                    k = j;
                }
                vA[k] = t;
                vI[k] = k;
            }
        }
    }

    Yes well I removed the error by just introducing a separate function for swap:

    Code:
    void switch_pos(int *one, int *two) {
    
    
       int temp = *one;
        *one = *two;
        *two = temp;
    }

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Sort and count frequency of array elements.
    By Nurlana in forum C++ Programming
    Replies: 12
    Last Post: 10-25-2012, 11:50 PM
  2. Replies: 8
    Last Post: 02-10-2010, 01:28 PM
  3. Sort an Array in Ascending Order ?
    By Coding in forum C++ Programming
    Replies: 5
    Last Post: 01-09-2008, 08:32 PM
  4. printing array elements in ascending order
    By galmca in forum C Programming
    Replies: 29
    Last Post: 10-24-2004, 11:24 PM
  5. Joining array elements and save in variable.
    By Nutshell in forum C Programming
    Replies: 12
    Last Post: 01-12-2002, 01:06 AM